Tuesday, January 27, 2009

Rails ActiveRecord validation

For something so simple, you'd think there'd be a decent amount of documentation out there for it, but you'd be wrong.

I was trying to write a validation on a model to ensure a certain condition was met, in this case that one object attribute was never larger than another for the same object before it was saved. Turns out it was as simple as this (sorry for the formatting, not sure how to post code snippets yet):
protected
_def validate
__errors.add_to_base('x cannot be greater than y') if self.x > self.y
_end
Apparently, Rails looks for a validate method and will call it during the validation process. No need for callbacks here (i.e. before_update, after_validation, etc.). The corresponding test is fairly easy to deduce:
it "should have not have more x than y" do
_@obj.y = 0
_@obj.x = 1
_@obj.should_not be_valid
end

No comments:

Post a Comment