[英]Rails Data Modelling: How can I model a has_many relationship that's actually a collection of another model?
更具體地說,我有一個User
模型has_one Profile
,現在我需要將一個has_many關系從User
添加到一個新模型Contact
,但是Contact
實際上是Profile
的集合(“ User has_many Profile ”在幕后)。
如何正確建模? 有沒有一種方法可以避免完全創建新的模型Contact
?
我的關注和提出這個問題的原因是必須執行效率低下的查詢才能檢索User Contacts 集合 : user.contacts
,然后對於每個Contact
我必須創建一個Query來檢索每個Profile
,對嗎?
如何做到這一點,以便在執行以下操作時: user.contacts
檢索不干擾/獨立於user.profile
關系的Profiles
集合?
提前致謝!
您不一定需要一個新的Model,但是擁有一個最簡單的模型(至少在我看來),只是沒有上面介紹的方式。
除了Rails,您還需要一個user_profiles
表,例如user_profiles
,其中包含user_id
和profile_id
外鍵。 現在,如何進行工作取決於您自己。
實際上,這里的Contact
模型實際上是一種更加Rails-y的UserProfile
模型。 因此,您的用戶可能看起來像:
class User
has_many :user_profiles # the join table
has_many :contacts, through: :user_profiles
has_one: profile
end
在這里, user.contacts
將為您提供個人資料。 您仍然擁有額外的模型UserProfile
,只是在實踐中不使用它:
class UserProfile
belongs_to :user
belongs_to :profile
end
您可以通過以下方式構建:
rails g model UserProfile user:references profile:references
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.