Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manually set error on a nested attribute in Rails 3?

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
like image 651
troynt Avatar asked Dec 20 '22 14:12

troynt


1 Answers

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
like image 171
numbers1311407 Avatar answered Mar 16 '23 13:03

numbers1311407