Data Validation with ActiveRecord in Ruby

Data validations are defined in Validations module of ActiveRecord. Each method in Validations module is designed to validate one and only one function. Examples of such validation methods are: validate_presence_of, and validate_length_of.

Examples of Data Validation is presented below given that Person class has two attributes: name, and title.

class Person < ActiveRecord:Base
 validates_presence_of %w{name}
 validates_length_of :title, :in=>1..100
end

person = Person.create
comment.errors.on ‘name’ //cannot be null
comment.errors[‘title’] //too short

We can see that our error checks fires appropriately for both validations since we are trying to create an empty object.

Every ActiveRecord has corresponding Errors objects. This object is empty initially, but as we encounter errors, it is being populated with these errors for saved for later retrieval. ActiveRecord uses this object before persisting data into database by checking it for existence of records. If Errors object is empty, then ActiveRecords saves into the database.

ActiveRecords has some other methods that help you validate data including requires_inclusion_of, validates_numericality_of. In addition, you can always custom build your own validation rules and you will be responsible for persisting it into Errors object just like built-in validations do now.

Validation rules can be selectively applied by passing :on option. For instance :on => :update or :on=>create. In the first instance, validation does not trigger the very first time but will trigger every time thereafter of your object creation.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…