通过关联belongs_to [英] belongs_to through associations
问题描述
鉴于以下关联,我需要从 Choice
模型中引用 Choice
附加的 Question
.我一直在尝试使用 belongs_to :question, through: :answer
来执行此操作.
Given the following associations, I need to reference the Question
that a Choice
is attached through from the Choice
model. I have been attempting to use belongs_to :question, through: :answer
to perform this action.
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 未初始化的常量 User::Choice
NameError uninitialized constant
User::Choice
当我尝试做 current_user.choices
它工作正常,如果我不包括
It works fine, if I don't include the
belongs_to :question, :through => :answer
但我想使用它,因为我希望能够执行validates_uniqueness_of
But I want to use that because I want to be able to do the validates_uniqueness_of
我可能忽略了一些简单的事情.任何帮助将不胜感激.
I am probably overlooking something simple. Any help would be appreciated.
推荐答案
belongs_to
关联不能有 :through
选项.您最好在 Choice
上缓存 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).
如果您有疑虑,请向 Choice
添加自定义验证,以确认答案的 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屋!