calling custom validation methods in Rails

Solution 1:

Your validations are executed when you use the validate method. However rails doesn't relies on the returned value.

It relies on if there are validations errors or not. So you should add errors when your model doesn't validates.

def something
    errors.add(:field, 'error message')
end

Or, if the error is not related to a field :

def something
    errors.add(:base, 'error message')
end

Then your model won't be saved because there are errors.

Solution 2:

You're getting confused between validations and callbacks.

Validations are supposed to fail if there are any errors on the object, doesn't matter what the validation returns. Callbacks fail if they return false, regardless if they add any errors to object.

Rails uses calls valid? from save calls which does not check the result of any validations.

Edit: Rails treats validate :method as a callback, but valid? still doesn't check for their results, only for errors they added to the object.

I don't think this behaviour changed at all but I could be wrong. I don't think I've ever written a validation to return false before.

Solution 3:

Just FYI errors.add_to_base('error message') has been deprecated in rails 3 and got replaced by

errors[:base] << "Error message" 

Or

errors.add(:base, "Error message")