开发者

Ruby on Rails: Is there a way to tell what fields failed validation in ActiveRecord?

I'm attempting to create an XML builder file that tells a user to know exactly what fields failed validation in the output. I also want to display their input back to them, so that requires me figuring out which fields failed validation. Meaning if someone fails on creating a new user resource, I want to display XML that's meaningful (Besides a meaningful HTTP status number) such as:

<errors>
    <user>
        <email>bad@email: Invalid email format</email>
    </use开发者_如何学Gor>
<errors>

The above is tough to do in an XML builder file without knowing what field failed. And if I just iterate over error messages, I won't know how to prob my @user object to get the value that the user supplied.


Use ActiveRecord::Errors#on

company = Company.create(:address => '123 First St.')
company.errors.on(:name)      # => ["is too short (minimum is 5 characters)", "can't be blank"]
company.errors.on(:email)     # => "can't be blank"
company.errors.on(:address)   # => nil

Or you can use ActiveRecord::Errors#each to get all attributes with errors

company = Company.create(:address => '123 First St.')
company.errors.each{|attr,msg| puts "#{attr} - #{msg}" }
# => name - is too short (minimum is 5 characters)
#    name - can't be blank
#    address - can't be blank


Straight from the API docs:

company.errors.each{|attr,msg| puts "#{attr} - #{msg}" } # =>
  name - is too short (minimum is 5 characters)
  name - can't be blank
  address - can't be blank

Isn't this what you're looking for: the attr variable will be the field name.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜