【问题标题】:Ruby on Rails: has_many referential --which model objects does it own?Ruby on Rails:has_many 引用——它拥有哪些模型对象?
【发布时间】: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


    【解决方案1】:

    但是,Rails 如何识别 follow_id 以链接到 User 对象?这 标签名称与用户不匹配,也没有 :class_name 指定。一世 只是不明白 Rails 是如何完成这项基础工作的,或者我错过了一些 提示。

    Rails 识别这是一个用户对象,因为它是在关系的 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>  ))
    

    【讨论】:

    • 我可以解释一下,通过belongs_to与Relationship模型的关联是成功的,因为User有:source=&gt;:followed,而Relationship也定义了belongs_to :followed?
    • 没错,正是因为如此,rails 才知道它是一个用户。
    【解决方案2】:
    has_many :following, :through=>:relationships, :source=>:followed
    

    这向 Rails 解释了 following 是 following 的反比关系,并且用户通过他的关系有很多关注和关注。

    Rails 知道 followed_id 链接到 User 的方式是它是在您的 Relationship 模型中定义的。

    希望你能理解!祝你好运:)

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      相关资源
      最近更新 更多