使用 accepts_nested_attributes_for 时验证其他模型的数据
Validates data of other model when accepts_nested_attributes_for is used
我属于并且有很多关系。
问题是我需要检查嵌套属性的分数字段是否小于 0,它不应该保存记录而不是 return 以形成错误消息。
我正在尝试的代码是:
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]"
I need to check if score
field from nested attributes is less 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
我属于并且有很多关系。
问题是我需要检查嵌套属性的分数字段是否小于 0,它不应该保存记录而不是 return 以形成错误消息。
我正在尝试的代码是:
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]"
I need to check if
score
field from nested attributes is less 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