Wednesday, December 15, 2010

Adding validations to Rails Appliaction

There are many ways to give validations in ruby on rails application.
One of the project I was working on needed something like this.
The fields in the database were cheque:boolean, cheque_no:integer, cheque_date:date, bank_name and other.
I wanted that without entering cheque_no, cheque_date and bank_name the user is not suppose to select the just checkbox of :cheque and update the record,
this can be done through javascript only by hiding the fields.
But the fields should be always visible.
So needed some nice validation over those fields.
the boolean cheque field can only get updated when the user enters other 3 fields.

So In model

validates_presence_of :cheque_no, :cheque_date, :bank_name , :if => :validate_presence_of_cheque?

# ----------- for adding validation on cheque_no, cheque_date, bank_name
def validate_presence_of_cheque?
cheque == true
end

I added the field as there were some more boolean fields on that record.

There are many ways to give validations in ruby on rails application.
But how many of us knows all of them.

The best place to find those is guides.rubyonrails.org.
Where we can get list of validations with examples.