Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

13.14. Validating Data with ActiveRecord

Problem

You want to prevent bad data from getting into your ActiveRecord data objects, whether the source of the data is clueless users or buggy code.

Solution

The simplest way is to use the methods defined by the ActiveRecord::Validations module. Each of these methods (validates_length_of, validates_presence_of, and so on) performs one kind of validation. You can use them to declare restrictions on the data in your object's fields.

Let's add some validation code to the Comment class for the weblog application first seen in Recipe 13.11. Recall that a Comment object has two main fields: the name of the author, and the text of the comment. We'll reject any comment that leaves either field blank. We'll also reject comments that are too long, and comments whose body contains any string from a customizable list of profane words.

	require 'cookbook_dbconnect'
	activerecord_connect
	
	class Comment < ActiveRecord::Base
	  @@profanity = %w{trot krip}
	  @@no_profanity_re = Regexp.new('^(?!.*(' + @@profanity.join('|') + '))')

	  validates_presence_of %w{author}
	  validates_length_of :content, :in => 1..200
	  validates_format_of :content, :with => @@no_profanity_re,
	                      :message => 'contains profanity'
	end

Comment objects that don't fit these criteria won't be saved to the database.

 comment = Comment.create comment.errors.on 'author' # => "can't be blank" comment.errors['content'] # => "is too short (minimum is 1 characters)" comment.save # => false comment = Comment.create(:content ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required