ruby - Rails Data Modelling: How can I model a has_many relationship that's actually a collection of another model? -
to more specific, have user
model has_one profile
, i'm in need add has_many relationship user
new model contact
, contact
collection of profile
s ("user has_many profiles" behind scenes).
how correctly model this? there way avoid creating new model contact
altogether?
my concern, , reason ask question having perform inefficient query retrieve user contacts collection: user.contacts
, each contact
i'd have create query retrieve each profile
, right?
how can make when do: user.contacts
retrieves collection of profiles
doesn't interfere/is independent of user.profile
relationship?
thanks in advance!
you wouldn't need new model, it's easiest (at least, in opinion) have one, not in way presented above.
rails aside, need join table, user_profiles
, contains foreign keys user_id
, profile_id
. now, how make work you.
your contact
model here actually, in more rails-y way, userprofile
model. user like:
class user has_many :user_profiles # join table has_many :contacts, through: :user_profiles has_one: profile end
here, user.contacts
profiles. still have model, userprofile
, don't use in practice:
class userprofile belongs_to :user belongs_to :profile end
which can build via:
rails g model userprofile user:references profile:references
hope helps!
Comments
Post a Comment