Raising Model Errors In Rails

6
Aug
1

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.
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BlinkList
  • MySpace
  • Netvouz
  • NewsVine
  • StumbleUpon
  • TwitThis
Filed under: Ruby, TechKnow
1 Comment

1 Comment

  1. Mike Boone
    10:55 am on June 17th, 2007

    Just what I was looking for. Thanks!

Leave a comment

RSS feed for comments on this post