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:
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: