【发布时间】:2017-11-16 15:20:02
【问题描述】:
我有 3 个模型:
User
has_many :questions
has_many :corrections
end
Question
has_one :correction
belongs_to :user
end
Correction
belongs_to :user
belongs_to :question
因此,如果用户 Bob 提出问题,则用户 Terry 可以检查它,如果错误提供更正。
让我们与 bob 保持联系,并假设他善意地纠正了 5 个其他用户,即假设他很幸运地得到了其他用户的 3 个更正。
我希望能够做这样的事情
@bob.corrections_offered => 5 个校正对象 @bob.corrections_received => 3 个更正对象
第一个很简单,因为它实际上只是 @bob.corrections 在引擎盖下。但我不知道如何实现后一个。有人可以帮忙吗?
更新
所以我尝试按照这样的建议使用 through(哦,实际上上面的问题模型实际上在我的代码中称为 Sentence。即 User => Sentence => Correction。)
has_many :sentences
has_many :corrections_received, :through => :sentences, :class_name => 'Correction'
但在控制台中出现此错误
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 找不到源 关联:模型中的更正 句子。尝试'has_many :corrections_received, :through => :句子,:来源=>'。是吗 之一:语言,:校正,:用户, 还是 :checker?
所以尝试了以下
has_many :corrections_received, :through => :sentences, :source => :correction
但是得到了
ActiveRecord::HasManyThroughSourceAssociationMacroError: 无效的源反射宏 :has_one 为 has_many :corrections_received, :through => :句子。使用 :source 指定 源反射。
不知道怎么回事……
【问题讨论】:
-
如果您将 has_one 替换为 has_many,它将起作用。
标签: ruby-on-rails activerecord