加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails如何获得ojbect的所有孙子孙女

发布时间:2020-12-17 02:51:07 所属栏目:百科 来源:网络整理
导读:我有3个型号: Userhas_many :questionshas_many :correctionsendQuestionhas_one :correctionbelongs_to :userendCorrectionbelongs_to :userbelongs_to :question 因此,如果用户Bob提出问题,那么用户Terry可以检查它,如果错误提供了更正. 让我们留下鲍勃,
我有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可以检查它,如果错误提供了更正.

让我们留下鲍勃,并假设他善意纠正其他5个用户,即让我们假设他很幸运能从其他用户那里获得3次更正.

我希望能够做这样的事情

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

第一个很容易,因为它真的只是引擎盖下的@ bob.corrections.但我不知道如何实施后者.有人可以帮忙吗?

UPDATE

所以我尝试使用通过如此建议(哦,实际上上面的问题模型实际上在我的代码中称为句子.I.e.User => Sentence => Correction.)

has_many :sentences
has_many :corrections_received,:through => :sentences,:class_name => 'Correction'

但在控制台中出现此错误

ActiveRecord::HasManyThroughSourceAssociationNotFoundError:
Could not find the source
association(s) :Correction in model
Sentence. Try ‘has_many
:corrections_received,:through =>
:sentences,:source => ‘. Is it
one of :language,:correction,:user,
or :checker?

所以尝试了以下内容

has_many :corrections_received,:source => :correction

但得到了

ActiveRecord::HasManyThroughSourceAssociationMacroError:
Invalid source reflection macro
:has_one for has_many
:corrections_received,:through =>
:sentences. Use :source to specify
the source reflection.

不确定什么是错的……

解决方法

您可以在用户模型中添加has_many through关系,如下所示

class User
  #your usual relationships
  has_many :corrections_received,:through => :questions,:class_name => 'Correction'
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读