【发布时间】:2011-08-30 08:28:45
【问题描述】:
我是 Rails 新手,完成了 Michael Hartl 的“Ruby on Rails 3 教程”。虽然这本书教会了我很多,但我发现这个谜题我不明白。
预览拼图,也就是看不懂,在User模型里面,
has_many :following, :through=>:relationship, :source=>:followed
这段代码如何将“user.following”链接到用户实例数组。
下面是整个谜题。
首先,我有 Relationship 模型,它记录了 followed_id 和 follower_id 信息。在 Relationship 模型中,关联很简单,如
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, :class_name => "User"
belongs_to :followed, :class_name => "User"
end
然后,在 User 模型中,用户将扮演 follower 的角色,并通过 relationships 收集关系表中的所有 following 行> 协会。
class User < ActiveRecord::Base
.
.
.
has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy
.
到现在为止,我明白了。
但是下一行出现了混乱,通过 user.following 它可以组装该用户的所有关注者(用户实例)。像这样,
has_many :following, :through=>:relationships, :source=>:followed
我知道 :source=>:followed 会覆盖默认值,并让我们找到与该用户关联的所有 followed_ids。
但是,Rails 如何识别followed_id 以链接到User 对象?标签名称与 users 不匹配,也未指定 :class_name。我只是不明白 Rails 是如何完成这项基础工作的,或者我错过了一些提示。
谢谢! :)
【问题讨论】:
标签: ruby-on-rails-3 model has-many model-associations