Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine ActiveModel::Errors validation type

With the migration from Rails 2 to Rails 3 validation errors were moved from ActiveRecord::Error to ActiveModel::Errors.
In rails 2 the validation error had a type and a message (among other things) and you could check the type of the validation error by doing something like the following:

rescue ActiveRecord::RecordInvalid => e
  e.record.errors.each do |attr, error|
    if error.type == :foo
      do_something
    end
  end
end

But with Rails 3 it seems everything but the invalid attribute and message has been lost. As a result the only way to determine the type is to compare the error message:

rescue ActiveRecord::RecordInvalid => e
  e.record.errors.each do |attr, error|
    if error == "foobar"
      do_something
    end
  end
end

Which is not at all ideal (eg. what if you have several validations which use the same message?).

Question:
Is there a better way in rails 3.0 to determine the type of validation error?

like image 427
pricey Avatar asked Aug 09 '12 10:08

pricey


1 Answers

Check for added? on ActiveModel::Errors:

https://github.com/rails/rails/blob/master/activemodel/lib/active_model/errors.rb#L331

That allows you to do this:

record.errors.added?(:field, :error)
like image 179
fkreusch Avatar answered Oct 11 '22 12:10

fkreusch