Is it possible to add errors to an ActiveRecord object without associating them with a particular attribute?

ruby-on-rails

Solution

Try doing something like this:

# Your Model.rb
validate :my_own_validation_method

...

private

def my_own_validation_method
    if there_is_no_sunday_in_the_range
        self.errors[:base] << "You must have a Sunday in the time range!"
    end
end

Basically, you can add your own complex validations to a model, and when you see that something erroneous has happened, you can add an error string in the array of errors.

Problem

If you need to code a considerably complex validation, the error sometimes doesnt lie in a particular attribute, but in a combination of several of them. For example, if i want to validate that a the time period between :start_date and :end_date doesnt contain any sunday, the error doesnt belong specifically to either of those fields, but the Errors add method requires to specify it.

Original source