开发者

Programmatic way of checking what validations failed in Rails

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开发者_StackOverflow


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


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.


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}"}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜