繁体   English   中英

has_many:通过Rails教程中的关联

[英]has_many :through association in the Rails tutorial

在Rails教程的最后一章中我什么都没得到。

因此,本章的目的是与其他用户建立友谊,并使其成为自我参照的协会。 (用户与其他用户有关系)

因此,在User模型中,有一个Friendship模型,它充当一个穿透表。

在代码中, 类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关联中指定我们要通过的表(Relationship table)。 但是在上面的代码中没有: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

所以,我的问题是,它如何工作?

汤姆斯

你说得对,你只有关系课。

默认情况下,在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

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 ,它是该对象的实际来源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM