请我需要帮助,以清楚说明此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”? 结果是什么样的?
答案 0 :(得分:2)
这是一个非常典型的设置,其中您有两个指向模型上同一表的外键关系。
为什么不使用基础模型名称“ relationship”代替 “ active_relationship”?
因为如果您创建两个具有相同名称的关联,则后者将覆盖前者。
例如,如果我们将示例修改为:
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :relationships, foreign_key: "followed_id", dependent: :destroy
当我们加入User.joins(:relationships)
时,Rails将创建查询JOINS relationships ON relationships.followed_id = users.id
。而且我们根本无法招募追随者。
这就是为什么您需要唯一的名称和关联。