Removing validations from a class in ActiveRecord

Ever wanted to remove validations from an ActiveRecord object, after you’ve defined them? For example, you’ve defined validations on a Member object, and you have an STI subclass called SpecialMembers. SpecialMembers are special and don’t have as many validations applied to them, so you want to ignore some of the validations placed by the super class.

Well. look no further. Paste the code below into lib/validations_extra.rb and require 'validations_extra' in environment.rb. You can then remove all the existing validations with a given name by putting remove_existing_validations(:<validation_name>) in your subclass definition; for example remove_existing_validations(:validates_presence_of). There’s not a more specific way to remove validations because ActiveRecord doesn’t provide one. You can remove all existing validations with remove_all_existing_validations. Enjoy!

This code works with Rails 2.0 and should work with later versions.

module ActiveRecord
  module Validations
    module ClassMethods
      def remove_existing_validations(key = :validate)
        write_inheritable_attribute(key, (read_inheritable_attribute(key) || []).select { |m| m.is_a?(Symbol) and m.to_s =~ /^validate_associated_records/ })
      end
      def remove_all_existing_validations
        [:validate, :validate_on_create, :validate_on_update].each { |m| remove_existing_validations(m) }
        define_method(:validate) {}
      end
    end
  end
end

05:18 PM on Thursday, 18/06/2009

Say something!