Rails如何获取对象的所有孙子

rob*_*sco 4 activerecord ruby-on-rails

我有3种型号:

User
has_many :questions
has_many :corrections
end

Question
has_one :correction
belongs_to :user
end

Correction
belongs_to :user
belongs_to :question
Run Code Online (Sandbox Code Playgroud)

因此,如果用户Bob提出问题,则用户Terry可以检查该问题,以及是否有错误提供了更正。

让我们呆在鲍勃身边,并假设他已善意地纠正了5个其他用户,即,并假设他很幸运地从其他用户那里获得了3次更正。

我希望能够做这样的事情

@ bob.corrections_offered => 5个校正对象@ bob.corrections_received => 3个校正对象

第一个很容易,因为它实际上是@ bob.corrections。但是我不知道如何实现后者。有人可以帮忙吗?

更新

因此,我尝试按照建议的方式使用直通车(哦,实际上,上面的问题模型在我的代码中实际上称为Sentence。即User => Sentence => Correction。)

has_many :sentences
has_many :corrections_received, :through => :sentences, :class_name => 'Correction'
Run Code Online (Sandbox Code Playgroud)

但是在控制台中出现此错误

ActiveRecord :: HasManyThroughSourceAssociationNotFoundError:在模型语句中找不到源关联:纠正。尝试'has_many:corrections_received,:through =>:sentences,:source =>'。是:language,:correction,:user或:checker之一?

所以尝试了以下

has_many :corrections_received, :through => :sentences, :source => :correction 
Run Code Online (Sandbox Code Playgroud)

但是得到了

ActiveRecord :: HasManyThroughSourceAssociationMacroError:无效的源反射宏:has_one for has_many:corrections_received,:through =>:sentences。使用:source指定源反射。

不知道出了什么问题...

nas*_*nas 5

您可以has_many through像这样在用户模型中添加关系

class User
  #your usual relationships
  has_many :corrections_received, :through => :questions, :class_name => 'Correction'
end
Run Code Online (Sandbox Code Playgroud)