Sunday, August 12, 2007

Rails Validations

Validation is nothing but a set of methods to ensure the integrity of information in the database. It forms a minimum standard that all records must meet before they can be saved.

Validation takes place before a model is saved. If the model being saved doesn’t meet its validation requirements, it will NOT be saved to the database. Attempts to save an invalid model return false. This allows for the “if-save” convention:

if @object.save
# object was valid and saved
..
else
# object was invalid, not saved
..
end

You can trigger validation manually by calling the models validate method.

@object.validate

But likely more useful would be to call valid?, which runs validate then returns true or false.

if @object.valid?
...

Avoiding validation

You can skip validation by passing false to save.

@object.save(false)

Similarly whenever "update_attribute" method is used, the validation for the
corresponding object is skipped. But if you use "update_attibutes" method,
It will trigger the validation methods for that object.

Note:
Skipping validtion may result (obviously) in invalid data being
recorded to the database.

Validation in Controllers:

When a model is validated, any validation errors will be collected in the models errors object.
you can use validation methods for an object in the controller class itself by just inspecting the object ( conditions ), and adding the errors to that object like this

@object.errors.add(:attribute,"#{error_messages}")