To be more specific, I have a User
model that has_one Profile
, now I'm in the need to add a has_many relationship from User
to a new model Contact
, but Contact
is really a collection of Profile
s ("User has_many Profiles" behind the scenes).
How do I correctly model this? Is there a way to avoid creating the new Model Contact
altogether?
My concern, and reason to ask this question is having to perform an inefficient query to retrieve the User Contacts collection: user.contacts
and then for each Contact
I'd have to create a Query to retrieve each Profile
, right?
How I can make it so that when I do: user.contacts
it retrieves a Collection of Profiles
that Doesn't interfere/is independent of the user.profile
relationship?
Thanks in advance!
You wouldn't be necessarily need a new Model, but it's easiest (at least, in my opinion) to have one, just not in the way presented above.
Rails aside, you need a join table, like
user_profiles
, which contains foreign keys foruser_id
andprofile_id
. Now, how you make that work is up to you.Your
Contact
model here is actually, in a more Rails-y way, aUserProfile
model. So your User could look like:Here,
user.contacts
would get you the profiles. You still have that extra model,UserProfile
, you just don't use it in practice:Which you can build via:
rails g model UserProfile user:references profile:references
Hope that helps!