在问题模型中
class Question
has_many :choices
accepts_nested_attributes_for :choices, :reject_if => ->(choice){ choice[:value].blank? }
validate :only_one_correct_answer
private
def only_one_correct_answer
unless (choices.select{ |choice| choice.correct }.size == 1)
errors.add(:choices, "You must provide only 1 correct answer")
end
end
end
在 HTML 表单中
<input name="question[choices_attributes][0][correct]" type="checkbox">
<input name="question[choices_attributes][1][correct]" type="checkbox">
<input name="question[choices_attributes][2][correct]" type="checkbox">
<input name="question[choices_attributes][3][correct]" type="checkbox"> ... till n
在 QuestionsController 中
@question = Question.new(params[:question])
@question.valid? => will automatically call Question#only_one_correct_answer and add errors,if any.
我希望这能帮到您。:)