Reputation: 2487
Is there a way to retrieve failed validations without checking the error message?
If I have a model with validates :name, :presence => true, :uniqueness => true
, how can I check if determine what validation failed(was it uniqueness or was it presence?) without doing stuff like:
if error_message == "can't be blank"
# handle presence validation
elsif error_message = "has already been taken"
# handle uniqueness validation
end
Upvotes: 2
Views: 239
Reputation: 3584
There's a relatively new method that let you do just that, it's not documented anywhere as far as I know and I just stumbled on it while reading the source code, it's the #added?
method:
person.errors.added? :name, :blank
Here's the original pull request: https://github.com/rails/rails/pull/3369
Upvotes: 3
Reputation: 13675
ActiveModel::Errors is nothing more than a dumb hash, mapping attributes names to human-readable error messages. The validations (eg. the presence one) directly add their messages to the errors
object without specifying where they came from.
In short, there doesn't seem to be an official way of doing this.
Upvotes: 2
Reputation: 3700
You can Haz all your errors in the errors method. Try this on an saved unvalid record :
record.errors.map {|a| "#{a.first} => #{a.last}"}
Upvotes: 1