【问题标题】:has_many :through association in the Rails tutorialhas_many : 通过 Rails 教程中的关联
【发布时间】: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


    【解决方案1】:

    你是对的,你只有 Relationship 类。

    默认情况下,在 Rails 中会有has_namy :relationships,那么您不必指定class name

    如果您不遵循 rails 默认规则,那么当您尝试使用 不同的关联名称 时,您必须指定 类名。

    在你的例子中

    has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
    

    您在此处指定从 Relationship 类中查找活动关系。

    has_many :through 指的是一个关联。

    has_many :following, through: :active_relationships,  source: :followed
    

    【讨论】:

      【解决方案2】:

      has_many :through 指的是关联,而不是表。 :source 是该关联所引用的类中的关系。

      在这种情况下

      has_many :followers, through: :passive_relationships, source: :follower
      

      指的是这种关系

      has_many :passive_relationships, class_name:  "Relationship",
                                     foreign_key: "followed_id",
                                     dependent:   :destroy
      

      在关系类中,有一个:follower,它是这个对象的实际来源。

      【讨论】:

      • Swards,我知道它指的是关联的名称而不是表(类),但我不知道在未指定关联时 rails 如何找到所需的表。 ..但我现在明白了,tnx :)
      • Swards,因此即使它是这样写的,关联也会起作用“has_many :followers, through: :relationship, source: :follower”
      • 我不这么认为——用户上没有has_many :relationship。它必须是明确提及的关联。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多