2017-07-28 36 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

相关问题