【问题标题】:Rails 4: Best schema for a User-Interests relationshipRails 4:用户利益关系的最佳模式
【发布时间】:2015-02-21 14:27:27
【问题描述】:

我是 Rails 新手,我试图充分利用模型之间可以指定的关系。这不是一个真正的编码问题,而是一个设计问题。我正在寻找有关在我的 Rails 应用程序中设置模型关系的最佳方法的特定问题的一些指导。

这是一个简单(且常见)的问题:

我有一个模型用户 我也有模特兴趣 用户会有很多兴趣,兴趣也会有很多用户, 因此,我创建了一个模型 UserInterest 来捕获这种关系,只需将 user_id 和 interest_id 作为表中的列。

我的第一个问题是:这是最好的方法吗?或者,我可以在 User 表中有一个兴趣列,并在其中放入一个 interest_id 数组。但是,在某些时候,我想根据兴趣搜索用户,因此使用连接表似乎是一种更好的方法。

第二个问题与创建和更新用户兴趣有关。如果使用上面的设置,那么每次用户在 users_interests 表中更新他的兴趣时,必须删除该用户的所有当前条目并创建一个新集合——这看起来很麻烦而且肯定是错误的。

【问题讨论】:

    标签: ruby-on-rails database model schema relationship


    【解决方案1】:
    class User < ActiveRecord::Base
     has_many :user_intrests
     has_many :intrests, through: :user_intrests
    end
    
    class UserIntrest < ActiveRecord::Base
     belongs_to :user
     belongs_to :intrest
    end
    
    class Intrest < ActiveRecord::Base
     has_many :user_intrests
     has_many :users, through: :user_intrests
    end
    

    你也可以向http://guides.rubyonrails.org/association_basics.html学习

    【讨论】:

      【解决方案2】:

      您的has_many through approach 是您给定问题的最佳选择。我只是不会使用UserInterest 作为模型名称。但这只是一个口味问题。

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 1970-01-01
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 1970-01-01
        • 2010-12-13
        相关资源
        最近更新 更多