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.