Raising Model Errors In Rails

Recently I covered rails’ model validators. I wanted to add a few more details regarding the validation methods. If a validation fails you can display an error message in the rhtml view by using the following code:

<%= error_messages_for 'user' %>

The parameter for error_messages_for is the name of an instance variable. An instance variable are those with the at sign, in this case @user. When creating, updating, or saving the @user instance if an error occurs the error_messages_for will create the HTML to display the error.

You can also directly add error messages to the model depending some business logic. In the controller you can add error messages to a model as follows:

@user.errors.add field_name, error_message

One thing to note is that adding errors to the model does not invalidate the model so you might want to save only if there are no errors.

if @user.errors.empty? && @user.save
  # successfully saved with no errors
else
  # Errors occurred, redirect to form
end

Technorati Tags: , , , ,

Enjoy. Share. Be Happy.
  • Twitter
  • Facebook
  • StumbleUpon
  • del.icio.us
  • Tumblr
  • Google Bookmarks
  • FriendFeed
  • Yahoo! Buzz
  • Reddit
  • Digg
  • HackerNews
  • Suggest to Techmeme via Twitter
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • Mixx
  • Furl

Related posts:

  1. Rails Model Validators
  2. Updating A Rails Plugin
  3. Common Groovy Errors
  4. Acts As Versioned Plugin
  5. Simply Helpful Rails Plugin

This entry was posted in Ruby, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted June 17, 2007 at 10:55 am | Permalink

    Just what I was looking for. Thanks!

  2. Posted September 7, 2009 at 9:39 pm | Permalink

    Your post save my life. :D Thanks!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*