【问题标题】:has_many :through in Active Record [closed]has_many:通过 Active Record [关闭]
【发布时间】: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


【解决方案1】:

这是一个相当典型的设置,其中有两个外键关系指向模型上的同一个表。

为什么不使用基础模型名称“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。而且我们根本无法获得追随者。

这就是您需要唯一名称和关联的原因。

【讨论】:

    猜你喜欢
    • 2012-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多