How to remove validation using instance_eval clause in Rails?
I found a solution, not sure how solid it is, but it works well in my case. @aVenger was actually close with his answer. It's just that the _validators
accessor contains only information used for reflection, but not the actual validator callbacks! They are contained in the _validate_callbacks
accessor, not to be confused with _validations_callbacks
.
Dummy.class_eval do _validators.reject!{ |key, _| key == :field } _validate_callbacks.reject! do |callback| callback.raw_filter.attributes == [:field] endend
This will remove all validators for :field
. If you want to be more precise, you can reject the specific validator for _validators
which is the same as the raw_filter
accessor of validate callbacks.
I think this is the most actual solution at this moment (I'm using rails 4.1.6):
# Common ninjaclass Ninja < ActiveRecord::Base validates :name, :martial_art, presence: trueend# Wow! He has no martial skillsNinja.class_eval do _validators[:martial_art] .find { |v| v.is_a? ActiveRecord::Validations::PresenceValidator } .attributes .delete(:martial_art)end