If you use Rails, you sometimes get a situation where the custom error messages just don’t work, here is how you can fix it…

Say you have a model with a field called ‘country_iso’ which specifies the ISO value of the country the person belongs to.

Database design concerns aside (you should really have it as country_id and a separate country_iso field) you might be stuck with this situation from a legacy database (like I was).

As this is a required field, you set the following in your model:

1
2
3
class User < ActiveRecord::Base
  validates_presence_of :country_iso
end

So, you go ahead and make a form which presents the country as just a select box, because you don’t want your users to worry about if Thailand is TH or TL, but then you don’t specify a country and the error message comes back to the user in nice big letters:

Country Iso can’t be blank

Ugh!

Aside from the fact that Iso is capitalized badly, how many of YOUR users know that it stands for “International Standards Organization” and that a Country ISO is usually a two letter representation of the country? I’d wager about 3 of them have some idea :)

So you go in and change the validates line to:

1
2
3
class User < ActiveRecord::Base
  validates_presence_of :country_iso, :message => "Country can't be blank"
end

Do your test again, and now you get:

Country Iso Country can’t be blank

Nup.. that’d didn’t really fix it.

Fortunately, the fix is easy:

1
2
3
4
5
class User < ActiveRecord::Base
  validate do |user|
    user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
  end
end

Now, reload your view and you’ll get:

Country can’t be blank

Much better!

blogLater

Mikel

  1. Ben Says:

    Hey Great Tip! Thanks for the post. Any idea how to make sure that the form field remains tagged properly with the appropriate error class so that the css rule for an error field will be applied properly? ~Ben

  2. Henrik N Says:

    Ben: You could also do http://henrik.nyh.se/2007/12/change-displayed-column-name-in-rails-validation-messages

  3. Victor Moroz Says:

    In fact I should have put this code to ApplicationController along with ActiveRecord::Errors.default_error_messages = { …

  4. Gianni Says:

    How to use it in error_messages_for ???

  5. marcao Says:

    I have found another way of doing this, I think it is simpler:
    Just keep the model with the validations statement, as you would normally

    validates_presence_of :country_iso, :message => “Sorry! Country can’t be blank”

    And then, in the view, change

    <% @client.errors.full_messages.each do |msg| %>
  6. <%= msg %>
  7. <% end %>

    to
    <% @user.errors.each do |attr,msg| >

  8. <
  9. = msg >
    < end %>

    And that’s it.
    This way you dont mess your css tags.
    @client.erros acctually returns a hash where the attribute is the key, and the msg is the value.

    by the way, great blog, have helped me alot.

  10. Henrik N Says:

    Ben: You could do http://henrik.nyh.se/2007/12/full-error-messages-without-prepended-attribute-name.

    I believe another way would be to add_to_base and then add a nil error to the attribute: user.errors.add(:country_iso, nil)

    nil errors should not be listed in text but still get you the CSS error highlighting.

  11. Mikel Says:

    Henrik: Nice solution! Go read Henrik’s solution, it’s quite neat!

  12. Vince Says:

    Is there a way to change the table name as well for the error message? For example, I have an STI model “class Group < Assembly” so when there is an error saving a Group, the error message says “2 errors prohibited this assembly from being saved” but I would like it to say “3 errors prohibited this group from being saved”.

  13. Luke Francl Says:

    The way I do this is by specifying full error messages for all my attributes, and then using a custom FormBuilder that displays the messages with the field (i.e., I do not use error_messages_for). With this approach, you get the benefit of having the error messages associated with the invalid attribute.

    I think the default messages are kind of like scaffolding: good for getting started, but I wouldn’t use them in a real app.

  14. Victor Moroz Says:

    I would suggest better way:

    class User < ActiveRecord::Base
    @@field_names = {
    :country_iso => ‘Country’
    }
    cattr_reader :field_names

    ActiveRecord::Errors.class_eval do alias user_add add def add(attribute, msg) user_add( User.field_names[attribute.to_sym] || attribute, msg ) end end

    Why? Because you can use all validates_… methods and regular error processing (how are you going to use validates_uniqueness_of?). Drawback – translation is application-wide, so User.country_iso and Session.country_iso will be translated exactly same way. Bad for existing applications where you can not choose fields.

  15. Peter Bernhauser Says:

    Great! I’d like to ask if there is a way to change default texts in header and bellow header:

    “5 errors prohibited this order from being saved
    There were problems with the following fields:”

    Reason – localization into different language
    Thanx

  16. simon Says:

    yea Peter go check out this page:
    http://www.softiesonrails.com/2008/4/23/better-messages-for-activerecord-validation-errors

  17. Victor Moroz Says:

    As for me I am using

    begin
    @User.save!
    rescue Exception => e
    flash.now[ :user_errors ] = e.message
    render :action => :new
    end

    Might not be the best thing of course, but resulting error message is concise and helps in case of other errors, not just database.

  18. Victor Moroz Says:

    Still don’t know how to paste code. You can check here -
    http://pastie.textmate.org/201339

    Meanwhile working example of my previous post can be found here (full translation of error messages & field names) –
    http://pastie.textmate.org/201340

    I happened to be a bit more complex than I expected.

  19. KreditMSKqoi Says:
    Деньги до миллиона, низкий % 8(495)769-53-05 Игорь (Москва)
  20. lemiPieftof Says:

    Children’s tooth development begins while the baby is in the womb. Teething usually occurs between the ages of six and nine months. Children usually have their full set of 20 primary teeth (milk teeth, baby teeth or deciduous teeth) by the age of three years. At about the age of six years, the first permanent teeth erupt (push through the gum).

  21. site Says:

    F*ckin’ amazing things here. I’m very glad to see your article. Thanks a lot and i am looking forward to contact you. Will you kindly drop me a e-mail? site

  22. CENTRUM EUROPY – szwedzki warszawa Says:

    This web page is really a stroll-via for the entire info you needed about this and didn’t know who to ask. Glimpse here, and also you’ll positively uncover it. CENTRUM EUROPY – szwedzki warszawa

  23. zespół na wesele bydgoszcz Says:

    Very nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your rss feed and I hope you write again soon! zespół na wesele bydgoszcz

  24. ALDO TECHNIKA GRZEWCZA SŁAWOMIR WIŚNIEWSKI Says:

    It’s laborious to seek out knowledgeable folks on this matter, however you sound like you know what you’re talking about! Thanks ALDO TECHNIKA GRZEWCZA SŁAWOMIR WIŚNIEWSKI

  25. PHU ALDO TECHNIKA GRZEWCZA SŁAWOMIR WIŚNIEWSKI Says:

    Good day! This post couldn’t be written any better! Reading this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing! PHU ALDO TECHNIKA GRZEWCZA SŁAWOMIR WIŚNIEWSKI

  26. ATGSW Says:

    Heya i am for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and help others like you helped me. ATGSW

  27. ALDO – pompy ciepła Says:

    I do agree with all the ideas you’ve presented in your post. They’re really convincing and will definitely work. Still, the posts are very short for novices. Could you please extend them a little from next time? Thanks for the post. ALDO – pompy ciepła

  28. kGygKevM Says:

    ]
    kGygKevM http://www.79KF7rE5EliB48Jl5Ar42Q.com/
    kGygKevM

  29. website Says:

    Howdy just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome. website

  30. hpv Białystok Says:

    Hi, I think your blog might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, terrific blog! hpv Białystok

  31. Prowadzenie ciąży Białystok Says:

    whoah this weblog is excellent i really like studying your posts. Stay up the great paintings! You understand, a lot of persons are searching round for this info, you could aid them greatly. Prowadzenie ciąży Białystok

Leave a Reply