我有以下情况
用户可以创建一个
的问题对于第一部分,我正在模型中尝试以下代码
“问题”模型
class Question < ActiveRecord::Base
has_many :answers
validate :at_least_two_answers
private
def at_least_two_answers
if answers.size < 2
errors[:base] << "Need at least 2 answers"
end
end
end
“答案”模式
class Answer < ActiveRecord::Base
belongs_to :question
end
但是我无法弄清楚如何为第二部分编写验证。我非常感谢有关如何为此编写验证的任何帮助。感谢。
答案 0 :(得分:2)
使用以下内容使您的错误消息更有意义:
count = answers.count { |a| a.is_correct? }
errors[:base] << (count == 0 ? "One answer should be correct" : "Only one answer can be correct") unless count == 1
答案 1 :(得分:1)
感谢您的帮助。计数的东西不起作用,因为我得到answers.count
为0.(必须是因为答案记录尚未创建)
但是对你的答案几乎没有修改我解决了这个问题。
validate :one_answer_right
def one_answer_right
count = 0
answers.each do |a|
if a.is_correct?
count += 1
end
end
errors[:base] << (count == 0 ? "One answer should be correct" : "Only one answer can be correct") unless count == 1
end