Validation levels: errors, warnings

Michael Schuerig
Fri, 02 May 2008 23:23:04 -0000

Normal validation messages tell the user that something is so terribly
wrong as to prohibit an object from saving. I recently had the
additional need to warn users that somethings fishy about their object
even though it doesn''t preclude saving it.

In that particular case fishiness only involved a custom validation
method and a new ''warning'' level

  def validates_not_fishy(options = {})
    level = options[:level] ?
      options[:level].to_s.pluralize.to_sym :
      :errors
    send(validation_method(options[:on] || :save)) do |record|
      if something_is_fishy
        # Instead of
        # record.errors.add_to_base("Something is wrong")
        # do
        record.send(level).add_to_base("Something is wrong")
      end
    end
  end

  def warnings
    @warnings ||= ActiveRecord::Errors.new(self)
  end

All of the above can, of course, be easily added to the classes where it
is needed, or duck punched into ActiveRecord. What I''d like to have is
a way to use the already existing validations for custom validation
levels, too. To be clear, I don''t want any further levels to be added
to AR, but I want the necessary hooks to add them myself in an app or
plugin.