Custom Validator

I want to add a custom validator in one of Model. For example Rails has
inbuilt validation methods like validates_uniqueness_of,
validates_presence_of . What I need is a similar kind of method
(example: validates_line_items), that can run my custom code while
saving, updating the record and can add custom error messages to the
record. Please help me by suggesting how i can do this.

You should probably purchase ‘Agile Development with Ruby on Rails’ from
http://www.pragmaticprogrammer.com/. It explains clearly how to use the
in built model methods;

validate
validate_on_create
validate_on_update

In these methods you can place any logic you want & add to the model
error object like so:

errors.add(:field_name, “error message”)

or

errors.add_to_base(“error message”)

Dipesh B. wrote:

I want to add a custom validator in one of Model. For example Rails has
inbuilt validation methods like validates_uniqueness_of,
validates_presence_of . What I need is a similar kind of method
(example: validates_line_items), that can run my custom code while
saving, updating the record and can add custom error messages to the
record. Please help me by suggesting how i can do this.

Have a look at validates_each. That allows you to perform validation
on an attribute (or attributes) with custom code.

validates_each :your_attribute do |model_instance, attribute, value|
# your
validation code here checking the value
end

-Michael
http://javathehutt.blogspot.com