belongs_to的通过协会 [英] belongs_to through associations

查看:143
本文介绍了belongs_to的通过协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我看一下这个。获得太累了。

can someone help me look at this. Getting too tired.

class User
  has_many :questions
  has_many :choices
end

class Question
  belongs_to :user
  has_many :answers
  has_one :choice, :through => :answer
end

class Answer
  belongs_to :question
end

class Choice
  belongs_to :user
  belongs_to :answer
  belongs_to :question, :through => :answer

  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
end

我得到一个NameError未初始化的常量用户::选择,当我尝试做current_user.choices

I am getting a NameError uninitialized constant User::Choice when I try to do current_user.choices

它工作正常,如果我不包括

It works fine, if I don't include the

belongs_to :question, :through => :answer

不过,我想用,因为我希望能够做的 validates_uniqueness_of

我可能俯瞰简单的东西。任何帮助将是AP preciated。谢谢!

I am probably overlooking something simple. Any help would be appreciated. Thanks!

推荐答案

A belongs_to的协会不能有一个:通过选项。你最好关闭缓存 question_id ,并加入了独特的索引表(特别是因为 validates_uniqueness_of 是容易出现竞争情况)。

A belongs_to association cannot have a :through option. You're better off caching the question_id on Choice and adding a unique index to the table (especially because validates_uniqueness_of is prone to race conditions).

如果你是偏执狂,添加自定义验证,以,确认这个答案的 question_id 比赛,但这听起来像最终用户不应该有机会提交数据,将造成这种不匹配的。

If you're paranoid, add a custom validation to Choice that confirms that the answer's question_id matches, but it sounds like the end user should never be given the opportunity to submit data that would create this kind of mismatch.

这篇关于belongs_to的通过协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆