我是Rails的新手,并完成了Michael Hartl的“Ruby on Rails 3 Tutorial”。虽然这本书教给我很多,但我发现这个难题我不明白。
在用户模型中预览拼图,即我不明白,
has_many :following, :through=>:relationship, :source=>:followed
这段代码如何将“user.following”链接到一个User实例数组。
以下是整个难题。
首先,我有关系模型,该模型记录 follow_id 和 follower_id 信息。在关系模型中,关联很简单,如
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, :class_name => "User"
belongs_to :followed, :class_name => "User"
end
然后,在用户模型中,用户将扮演关注者的角色,并通过关系关注行>协会。
class User < ActiveRecord::Base
.
.
.
has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy
.
到现在为止,我明白了。
但是下一行出现了混乱,通过 user.following ,它可以汇集所有用户的以下内容(用户实例)。像这样,
has_many :following, :through=>:relationships, :source=>:followed
我了解:source =&gt ;: follow 会覆盖默认设置,并找到与该用户关联的所有 follow_ids 。
但,Rails如何识别 follow_id 以链接到用户对象?标签名称与用户不匹配,也未指定:class_name 。我只是不知道Rails如何做这个基础工作,或者我错过了一些提示。
谢谢! :)
答案 0 :(得分:1)
但是,Rails如何识别follow_id链接到User对象?该 标签名称与用户不匹配,也没有:指定class_name。一世 只是不知道Rails如何做这个基础工作,或者我错过了一些 提示。
Rails认识到这是一个用户对象,因为它是在Relationship的belongs_to中设置的。 Rails在这里做的是通过外键“follower_id”跟随关系类,并返回与当前用户有关系的每个用户。当然,Rails在单个SQL语句中执行此操作:
SELECT `users`.* FROM `users` INNER JOIN `relationships` ON `relationships`.followed_id = `users`.id WHERE ((`relationships`.follower_id = <the current user id> ))
答案 1 :(得分:0)
has_many :following, :through=>:relationships, :source=>:followed
这向Rails解释following
是following
的反向关系,并且用户有许多关注并遵循他的关系。
Rails知道followed_id
与用户关联的方式是它在Relationship
模型中定义。