因此,在第12章或Hartl的Railstutorial中,我们正在为用户建立关注彼此"twitter"提要的能力。这被建模为用户形成关系,我们创建了一个具有follower_id和followed_id的表的关系模型。同样在模型中,我们将其与用户模型关联如下:
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
end
我们还将用户模型与关系模型关联如下:
class User < ActiveRecord::Base
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
我很困惑为什么我们需要在用户模型中使用has_many:following。教程中说,关注某人是一种积极的关系,那么为什么我们需要说用户有很多积极的关系呢?用户也在关注很多(这是一种活跃的关系)。has_many:active_relationships不能做的事情到底是什么?
我的第二个问题是,为什么belongs_to被拆分为follower和follow,而不仅仅是user。使用两个belong_to而不是仅在用户上使用一个,我们会得到什么?
这是一种访问特定用户后面或后面的Users
而不是关系的方法。
如果您只有@user.active_relationships
,它将返回联接表中的关系。但是使用@user.following
可以得到User
对象的关联数组。
至于您的第二个问题,两个用户之间的关系需要两个对象,而不是一个对象,并且只有一个belongs_to :user
是毫无意义的。
RubyonRails指南-关联|有很多:通过