What is the correct naming convention for linked tables and models in rails 3

I have two types of users in my application, Investors and Advisors , they have both a separate model and a table in the database (investor model, advisor model, investors table and advisors table).

I need to create a table to save the advisor profile data and another table to save the investor profile (they have completely different fields in the profile, so I cannot merge into one table). What name should I give him? If I call it investor_profile - then every time I want to get data from it I have to call it investor->investor_profile->field_name

, but it seems wrong to enter the investor twice.

Any recommendations for your own name? Or maybe a trick to do it investor->profile->field_name

?

Thank.

+3


source to share


3 answers


You can store different tables for investor_profiles

and advisor_profiles

with separate models InvestorProfile, AdvisorProfile

(which both can inherit from the base class Profile

, assuming they have at least a tiny bit of overlap).

But in your model associations, use the option :class_name

to hide _profiles

:

class Investor < ActiveRecord::Base
 has_one :profile, :class_name => "InvestorProfile" 
end


class Advisor < ActiveRecord::Base
 has_one :profile, :class_name => "AdvisorProfile" 
end

# And since the profiles probably overlap in some way
# a profile base class which the other 2 profile classes extend
class Profile < ActiveRecord::Base
  # base options like name, address, etc...
end  
class InvestorProfile < Profile
  # Investor-specific stuff
end
class AdvisorProfile < Profile
  # Advisor-specific stuff
end

      



In practice, then you can refer to it as self.profile

:

# Use it as
adv = Advisor.new
puts adv.profile.inspect

      

For a description of the parameters, see the documentation ActiveRecord::Associations

.

+2


source


I believe it makes sense to have investor_profile and advisor_profile if they are different and therefore you cannot use the same model.

Don't worry about accessing and repeating names, because you can do this:



class Investor
     has_one :profile, class_name: "InvestorProfile"
end

      

And given the Investor object, you should be able to do things like @investor.profile.profile_field

+2


source


You can name the association whatever you want and specify the name of the model class:

class InvestorProfile < ActiveRecord::Base
  # Investor_profiles table must contain an investor_id column
  belongs_to :investor
end

class Investor < ActiveRecord::Base
  # Thanks to the :class_name option rails know what a profile is
  has_one :profile, :class_name => "InvestorProfile"
end

      

and then you can access the profile fields using something like this @investor.profile.field_name

.

+1


source







All Articles