How do I manually set error on a nested attribute in Rails 3?
The following is some example model code that I tried and isn't working for me.
validate :matching_card_colors
has_many :cards
accepts_nested_attributes_for :card
def matching_card_colors
color = nil
cards.each do |card|
if color.nil?
color = card.color
elsif card.color != color
card.errors.add :color, "does not match other card colors"
end
end
end
The secret is in where you put the errors. Check out how validations with autosave associations work for a clue:
def association_valid?(reflection, record)
return true if record.destroyed? || record.marked_for_destruction?
unless valid = record.valid?(validation_context)
if reflection.options[:autosave]
record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}"
errors[attribute] << message
errors[attribute].uniq!
end
else
errors.add(reflection.name)
end
end
valid
end
Note how the errors aren't added to the association members, but rather to the record being validated, the offending attribute prefixed with the association name. You should be able to do this as well. Try something like:
def matching_card_colors
color = nil
cards.each do |card|
if color.nil?
color = card.color
elsif card.color != color
# Note, there's one error for the association. You could always get fancier by
# making a note of the incorrect colors and adding the error afterwards, if you like.
# This just mirrors how autosave_associations does it.
errors['cards.color'] << "your colors don't match!"
errors['cards.color'].uniq!
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With