Reputation: 8189
The question sums it up. Is it possible to have a custom validation respond by simply not saving a record, rather than throwing an error? As far as I know, the only way to write a custom validation is by invoking an error like this:
def at_least_one_attribute_has_changed
if no_changes?
errors[:base] << I18n.t("activerecord.errors.messages.we_did_not_detect_any_changes")
end
end
Perhaps there's a gentler method? Some mystical skip_save
call that I'm unfamiliar with?
Upvotes: 1
Views: 1605
Reputation: 14038
Do you specifically want to have validation fail without a message, or do you want to try to save an object and fail without errors if the object is invalid?
For the former you may be out of luck, the .valid?
call checks for errors on an object, so if you don't have any messages the object will count as valid.
For the latter you could clear the errors or reload the object if save fails, whichever is appropriate to your use case.
unless @object.save
@object.errors.clear # if object has had attributes changed this will preserve those changes but remove the errors.
end
If you provide more information on why you want to do this there may be a more appropriate response.
Upvotes: 2