Rails 4:用户兴趣关系的最佳模式

Rails 4: Best schema for a User-Interests relationship

我是 rails 的新手,正在尝试充分利用可以在模型之间指定的关系。这实际上不是编码问题,而是设计问题。我正在寻找有关在我的 Rails 应用程序中建立模型关系的最佳方式的特定问题的一些指导。

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

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

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

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

你的 has_many through approach 是你给定问题的最佳答案。我只是不会使用 UserInterest 作为模型名称。但这只是一个品味问题。

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