I have belongs to and has many relation.
The problem is that I need to check if score field from nested attributes is less 0, it should not save records instead return to form with error message.
The code I am trying is:
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
The form field looks like that containing array:
name="quiz_attempt[quiz_answers_attributes][5][score]"
Aucun commentaire:
Enregistrer un commentaire