使用accepts_nested_attributes_for时,验证其他模型的数据

时间:2016-10-14 10:25:40

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 rails-activerecord

我属于且有很多关系。

问题是我需要检查嵌套属性中的得分字段是否小于0,它不应该保存记录而是返回带有错误消息的表单。

我正在尝试的代码是:

class QuizAttempt < ActiveRecord::Base

  has_many :quiz_answers
  accepts_nested_attributes_for :quiz_answers, reject_if: :invalid_score

  validate :score_greater_than_zero

  private

  def score_greater_than_zero
    errors.add(:quiz_answers, 'must greater than 0') if invalid_score(attributes)
  end

  def invalid_score(attributes)
    attributes['score'].to_i > 0
  end
end


class QuizAnswer < ActiveRecord::Base
  belongs_to :quiz_attempt
end

表单字段看起来像包含数组:

name="quiz_attempt[quiz_answers_attributes][5][score]"

1 个答案:

答案 0 :(得分:1)

  

我需要检查嵌套属性中的score字段是否小于0

您需要访问嵌套对象(quiz_answers)并检查其属性,而不是quiz_attempt的属性:

  def score_greater_than_zero
    if quiz_answers.any? { |answer| answer.score <= 0 }
      errors.add(:quiz_answers, 'must be greater than 0')
    end
  end