Ruby on rails 在Rails教程中有很多:通过关联
在Rails教程的最后一章中,我没有得到任何东西 因此,本章的目的是与其他用户建立友谊,这使其成为一种自我参照的关联。(用户与其他用户有关系) 因此,对于用户模型,有一个友谊模型,它充当一个直通表 在代码中,类用户Ruby on rails 在Rails教程中有很多:通过关联,ruby-on-rails,has-many,self,self-reference,Ruby On Rails,Has Many,Self,Self Reference,在Rails教程的最后一章中,我没有得到任何东西 因此,本章的目的是与其他用户建立友谊,这使其成为一种自我参照的关联。(用户与其他用户有关系) 因此,对于用户模型,有一个友谊模型,它充当一个直通表 在代码中,类用户 class User < ActiveRecord::Base has_many :microposts, dependent: :destroy has_many :active_relationships, class_name: "Relationship",
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:through关联中指定我们要处理的表(关系表)。但是在上面的代码中没有
:主动关系或:被动关系表,只有一个关系类
关系表:
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汤姆你说得对,你只是有了一段关系 在rails中,默认情况下会有
has\u namy:relationships
,那么您不必指定类名
如果您没有遵循rails默认规则,那么当您尝试使用不同的关联名称时,您必须指定类名
在你的例子中
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
这里指定从关系类中查找活动关系
has__许多:through指的是一个关联
has_many :following, through: :active_relationships, source: :followed
has_许多:through指的是一个关联,而不是一个表。:源是该关联所引用的类中的关系
在这种情况下
has_many :followers, through: :passive_relationships, source: :follower
指的是这种关系
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
在relationship类中,有一个:follower
,它是这个对象的实际源。Swards,我知道它指的是关联的名称,而不是表(类),但我不知道rails在没有指定关联的情况下如何找到所需的表……但是我现在知道了,tnx:)Swards,所以,即使是这样写的“has_many:followers,through::relationship,source::follower”,这个关联也会起作用。我不这么认为——在用户上没有has_many:relationship
。它必须是明确提到的关联。
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy