Ruby on Rails 3.0 – Active Model and New Validations

Just came across the Ruby on Rails 3.0 Beta release. There are a lot of exciting new features and it all seems exciting. Something that caught my eye was Active Model and new validations. So here I am, jotting them down for myself and all those who might be interested in reading about it.

New in Rails 3.0, Active Model provides an abstraction layer for any ORM libraries. Now all new ORM plugins need to implement the Active Model interface and they would work fine with Action Pack.

Validations have been moved from Active Record to Active Model.

A new shortcut method has been introduced which allows you to pass more than one option to all the validates class methods. This new method is

validates :attribute, options_hash

The validates method has the following options:

:acceptance => Boolean.
:confirmation => Boolean.
:inclusion => { :in => Ennumerable }.
:exclusion => { :in => Ennumerable }.
:length => { :maximum => Fixnum }.
:format => { :with => Regexp, : on => :create }.
:numericality => Boolean.
:presence => Boolean.
:uniqueness => Boolean.

So, for example,

# app/models/student.rb

class Student < ActiveRecord::Base
  validates :name,  :presence => true,
                    :length => {:minimum => 5, :maximum => 120}

  validates :email, :presence => true,
                    :length => {:minimum => 6, :maximum => 150},
                    :uniqueness => true,
                    :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}


Will be back with more of 3.0 Rails. Therez a lot to cover🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s