Smoke Signals

Monday, February 21, 2005

Catching errors in rails

For those times when users don't fill out their info correct. Here is how you can handle that in rails... First off read: Active Record API doc That will give you a good idea of what you can catch.

Then to implement: In your model class add a validation check - validates_presence_of :description, :message => "is a required field!"

In your controller class add a class instance var of what you are trying to save with the model. For instance in the todo tutorial you have

def add_item

item = Todo.new # Create a new instance of Todo, so create a new item

@todo = item


The @todo will be used in your html to render the error. Now in your add_item.rhtml template(named after the method) you put either 2 things. <% @todo.errors.each_full do |message| %>

<%= message %>

<% end %>

This will iterate over every error and output its message. Doing this: <%= error_messages_for "todo" %> will give you a bit more but you have less control over the formatting

1 Comments:

Post a Comment

<< Home