【发布时间】:2015-09-17 07:33:44
【问题描述】:
我在 Rails 教程的最后一章没有得到什么。
所以本章的目的是与其他用户建立友谊,这使它成为一个自我参照的关联。 (用户与其他用户有关系)
因此,对于 User 模型,还有 Friendship 模型,它充当直通表。
在代码中,class User
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
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
.
.
.
end
但我不明白这部分:
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
我们必须在 has_many :through 关联中指定我们正在经历的表(关系表)。但是在上面的代码中没有 :active_relationships 或 :passive_relationships 表,只有一个 Relationship 类。
关系表:
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
所以,我的问题是,它是如何工作的?
Tnx 汤姆
【问题讨论】:
标签: ruby-on-rails has-many self self-reference