一个用户可以有很多:
user.rb 的代码如下所示:
class User < ActiveRecord::Base
# follower_follows "names" the Follow join table for accessing through the follower association
has_many :follower_follows, foreign_key: :followee_id, class_name: "Follow"
# source: :follower matches with the belong_to :follower identification in the Follow model
has_many :followers, through: :follower_follows, source: :follower
# followee_follows "names" the Follow join table for accessing through the followee association
has_many :followee_follows, foreign_key: :follower_id, class_name: "Follow"
# source: :followee matches with the belong_to :followee identification in the Follow model
has_many :followees, through: :followee_follows, source: :followee
end
follow.rb 的代码如下:
class Follow < ActiveRecord::Base
belongs_to :follower, foreign_key: "follower_id", class_name: "User"
belongs_to :followee, foreign_key: "followee_id", class_name: "User"
end
最需要注意的可能是user.rb 中的:follower_follows 和:followee_follows。以磨坊(非循环)关联为例,一个团队可能有多个:players 到:contracts。这对于 玩家 来说并没有什么不同,他们可能也有很多:teams 到:contracts(在这样的玩家 的职业生涯中)。
但是在这种情况下,只有一个命名模型存在(即用户),相同地命名 through: 关系(例如through: :follow)将导致不同用例的命名冲突(或访问点)连接表。创建:follower_follows 和:followee_follows 是为了避免这种命名冲突。
现在,一个用户可以拥有多个:followers到:follower_follows和多个:followees到:followee_follows:
- 为了确定 User 的 :followees(在对数据库的
@user.followees 调用时),Rails 现在可以查看 class_name 的每个实例:“Follow”,其中此类用户是关注者(即foreign_key: :follower_id)通过:这样的用户的:followee_follows。
- 为了确定 User 的 :followers(在
@user.followers 调用数据库时),Rails 现在可以查看 class_name 的每个实例:“Follow”,其中此类 User 是被关注者(即foreign_key: :followee_id),通过:这样的用户的:follower_follows。