簡體   English   中英

Rails數據建模:如何為實際上是另一個模型集合的has_many關系建模?

[英]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_idprofile_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM