【发布时间】:2020-09-08 22:58:15
【问题描述】:
请帮助我清楚地解释此 Rails 代码中发生的情况:
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
为什么不使用基础模型名称“relationship”而不是“active_relationship”? 结果如何?
【问题讨论】:
-
查看前两个
has_manys 上的foreign_key:选项。一个给你追随者,另一个给你追随者。has_many ... through:关联绕过Relationship加入模型,直接进入关注者和关注者(可能是某种用户或个人模型)。 -
@dbugger 这与多重继承完全无关。它是一个连接表,两次指向同一个表。
标签: ruby-on-rails activerecord associations has-many-through