在rails 3中添加自定义验证

时间:2013-08-14 12:11:23

标签: ruby-on-rails-3 activerecord ruby-on-rails-3.1 ruby-on-rails-3.2

我正在使用嵌套模型,一个问题有多个答案,只有一个可以被标记为正确我如何验证以检查只有一个问题被标记为正确。正确的是布尔字段。

#question model
validate :one_correct_answers

  def one_correct_answers
    if self.choices.correct_choices > 1
      errors.add(:base, "please select only one correct answer")
    end
  end

2 个答案:

答案 0 :(得分:1)

问题模型

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.

我希望,这会对你有所帮助。 :)

答案 1 :(得分:0)

首先,您的复选框应如下所示:

<input id="something_" name="something[]" type="checkbox" value="<%= some_id %>">

这样,当您提交表单时,参数应该与已选中的复选框一样:

params: something => [1, 2]

然后,在控制器上将变量correct_choices设置为此数组,并使用自定义验证程序进行验证。