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: , , , ,


2 Responses to “Raising Model Errors In Rails”

Leave a Reply