Thursday, July 13, 2006

Validation in Rails

Let's try our hand at some validation. No participant should be allowed in the database if it has an empty text field or an invalid URL for the blog_url. So, where do we put the validation? The model layer is the gatekeeper between the world of code and the database. Nothing to do with our application comes out of the database or gets stored back into the database that doesn't first go through the model.

This makes it an ideal place to put all validation; it doesn't matter whether the data comes from a form or from some programmatic manipulation in our application. If the model checks it before writing to the database, then the database will be protected from bad data.

Let's look at the source code of the model class (in app/models/participant.rb).
class Participant < ActiveRecord::Base
end
Not much to it, is there? All of the database mapping, creating, updating, searching, and so on is done in the parent class (ActiveRecord::Base, a part of Rails). Because of the joys of inheritance, our Participant class gets all of that functionality automatically.

Let's start by validating that the text fields all contain something before a row is written to the database. We do this by adding some code to the existing model, as follows:
class Participant < ActiveRecord::Base
validates_presence_of :name, :city, :blog_url
end
The validates_presence_of( ) method is a standard Rails validator. It checks that a given field, or set of fields, is present and its contents are not empty. The screen shot, shows what happens if we try to submit a new product with none of the fields filled in. It's pretty impressive: the fields with errors are highlighted, and the errors are summarized in a nice list at the top of the form. Not bad for one line of code. You might also have noticed that after editing the participant.rb file you didn't have to restart the application to test your changes. Rails notices that the files have been changed and reloads them into the application. This is a tremendous productivity boost when developing.

We also want to make sure that each partcipant has a unique blog_url. One more line in the Participant model will do this. The uniqueness validation will perform a simple check to ensure that no other row in the participants table has the same blog_url as the row we're about to save.
validates_uniqueness_of :blog_url

First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

1 Comments:

Blogger Aspirations said...

This is fantastic.

No reboot required for changes to take effect...no compilation, nothing.

It's impressive and fast.

2:30 PM  

Post a Comment

<< Home