2017-07-28 33 views
1

更具體,我有一個User模型HAS_ONEProfile,現在我需要從User添加的has_many關係提高到一個新的模式Contact我,但Contact是真正的Profile個集合( 「用戶has_many配置文件 s」在幕後「。Rails數據建模:我如何建模一個has_many關係,它實際上是另一個模型的集合?

basic diagram

如何正確模擬呢?有沒有辦法避免一起創建新型號Contact

我的關注,有理由問這個問題是必須進行低效的查詢檢索用戶聯繫人收集user.contacts,然後爲每個Contact我不得不創建一個查詢檢索每個Profile,對不對?

我怎樣才能讓這個當我這樣做:user.contacts它檢索的Collection Profiles干擾/獨立於user.profile關係?

提前致謝!

回答

2

你不一定需要一個新的模型,但它是最簡單的(至少在我看來)有一個,只是沒有在上面提出的方式。除了導軌之外,您需要一個連接表,如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

希望幫助!

+0

它的確有很大幫助,謝謝!有一點後續問題,Migration for UserProfiles Model會如何? – jlstr

+1

@jlstr我更新了我的答案,包括模型和遷移細節 – GoGoCarl

+0

太棒了!先生非常感謝您! – jlstr

相關問題