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