41

I would like to enhance existing class using instance_eval. There original definition contains validation, which require presence of certain fields, ie:

class Dummy < ActiveRecord::Base
  validates :field, :presence => true 
end

Now I want to change that to optional using instance_eval (or any other method, really):

Dummy.instance_eval do
  ...
end

What would be the proper syntax to remove the validation, so the field is optional. I would rather do this directly on the model layer, instead doing weird hacks in controllers or views. The use of instance_eval is not really required, but as far as I know, this is generally the best way to enhance classes in Rails.

Edit #1

In general - the original class is part of the gem and I don't want to fork it, nor tie to specific release. The general cause is not really important. Simply editing the original model has far worse consequences than monkey patching.

12
  • 3
    Please don't do this. Just go edit the model.
    – thomasfedb
    Sep 25, 2011 at 14:03
  • 1
    instance_eval is not the best way to enhance classes in rails, any more than a chainsaw is the best way to cut a two-by-four. What is the enhancement you are trying to achieve, and why? Sep 25, 2011 at 14:09
  • 2
    If you want to remove the validation, why have you added it in the first place? It sounds like you want conditional validation (search for :if).
    – rdvdijk
    Sep 25, 2011 at 14:18
  • 1
    This isn't just a technical problem, it's an organizational one. Why has your group or organization gotten itself on the ropes with Rails code it cannot modify? Whatever the technical solution to your immediate problem, that problem needs solving. Sep 26, 2011 at 15:59
  • 30
    geez there's a few unhelpful, sanctimonious comments here, IMO. How about you drop the attitude and assume that the poster knows what they are doing.
    – nocache
    Apr 17, 2013 at 0:55

18 Answers 18

30

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]
  end
end

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.

5
  • 2
    BTW, yes... this is evil, but can be useful for monkey patching a gem that contains validation rules that you find too strict! DON'T DO THIS AT HOME! ;-) Jun 29, 2012 at 21:05
  • Thanks Nicolas, the _validators attribute is exactly what I was looking for. Aug 8, 2012 at 18:22
  • 3
    Doesn't work anymore with rails 4.1 because _validate_callbacks is not an array anymore, but includes Enumerable, so trying out using reject instead of reject! now...
    – Nico
    Feb 25, 2014 at 13:01
  • 1
    Scroll down to my answer. Works with 4.1.6
    – 18augst
    Nov 17, 2014 at 2:22
  • As for Rails 4.2.6 this seems to be the working example: gist.github.com/brenes/4503386
    – jmarceli
    Mar 16, 2016 at 8:27
13

I think this is the most actual solution at this moment (I'm using rails 4.1.6):

# Common ninja
class Ninja < ActiveRecord::Base
  validates :name, :martial_art, presence: true
end

# Wow! He has no martial skills
Ninja.class_eval do
  _validators[:martial_art]
    .find { |v| v.is_a? ActiveRecord::Validations::PresenceValidator }
    .attributes
    .delete(:martial_art)
end
3
  • 2
    Yes! Finally worked... Can also use Ninja.validators_on now
    – Oded Niv
    Jun 11, 2017 at 8:44
  • This should be the accepted answer. It's very explicit as to what it's doing.
    – Passer by
    Feb 28, 2018 at 16:54
  • 1
    Using Rails 5, I ended up using this one line. In Ninja class, I added: self.validators_on(:name).each { |val| val.attributes.delete(:name) }
    – Nanego
    Dec 18, 2019 at 12:34
13

Easest way to remove all validations:

clear_validators!
10

As I was trying to do this to remove the phone validation from the spree Address model, below is the code I got to work. I added the type check for callback.raw_filter because I only wanted to remove the presence validator on the phone field. I also had to add it because it would fail when trying to run against one of the other validators specified in the Spree::Address model that did not have an 'attributes' key for callback.raw_filter, thus an exception was thrown.

Spree::Address.class_eval do

   # Remove the requirement on :phone being present.
  _validators.reject!{ |key, _| key == :phone }

  _validate_callbacks.each do |callback|
    callback.raw_filter.attributes.delete :phone if callback.raw_filter.is_a?(ActiveModel::Validations::PresenceValidator)
  end

end
0
5

I had a similar problem and was able to get past it using:

class MyModel << Dummy
  # erase the validations defined in the plugin/gem because they interfere with our own
  Dummy.reset_callbacks(:validate)
  ...
end

This is under Rails 3.0. The caveat: It does remove ALL validations, so if there are others you want to keep you could try Dummy.skip_callback(...), but I could not figure out the right incantation of arguments to make that work.

3

One solution is to extend validates :

#no need of instance_eval just open the class
class Dummy < ActiveRecord::Base
  #validates :field, :presence => true 

  def self.validates(*attributes)
    if attributes.first == :field #=> add condition on option if necessary
      return # don't validate
    else
      super(*attributes) #let normal behavior take over
    end
  end
end

And no that's not monkey-patching but extending or decorating a behavior. Rails 3.1 is built on the idea of "multi- inheritance" with module inclusion, specifically to allow this kind agility.

update #2

One caveat is you must load the class with the redefined validates method before the gem containing the call to validates. To do so, require the file in config/application.rb after require "rails/all" as suggested in the railsguides. Something like that :

require File.expand_path('../boot', __FILE__)

require 'rails/all' # this where rails (including active_record) is loaded
require File.expand_path('../dummy' __FILE__) #or wherever you want it

#this is where the gems are loaded...
# the most important is that active_record is loaded before dummy but...
# not after the gem containing the call to validate :field
if defined?(Bundler)
  Bundler.require *Rails.groups(:assets => %w(development test))
end

Hope it works now!

7
  • I can't get this to work. It seems, that this will do only for validations specified after the method override. I have no idea if and how can I get this to load before the class from the Gem is loaded...
    – mdrozdziel
    Oct 5, 2011 at 16:53
  • You're right self.validates should be redefined before it is called. I guess the best place would be in an initializer. Not totally sure about that... Otherwise I did a quick test and the trick worked... Just beware that I forgot the little star in super(*attributes) - corrected. Oct 5, 2011 at 19:39
  • @acidburn2k did you try out my last suggestion ? would love feedback on this : it's an interesting problem you came up with. Oct 7, 2011 at 12:56
  • It's an interesting idea, but it did not work. The reason is, that if you define ActiveRecord before including Rails, the things will start to break as soon as Rails are included. I believe there are places with calls to check if ActiveRecord was already defined and include if it wasn't. In this case it is defined, but it is simply missing all the code inside... In this particular case Delayed::Job is failing to find set_table_name inside ActiveRecord. :(
    – mdrozdziel
    Oct 11, 2011 at 6:48
  • I just discovered you can actually do something much easier : require the file in your Gemfile like so just after gem rails : require "lib/dummy" that way active record is loaded but not the gem yet. Oct 11, 2011 at 9:59
3

Answer by aVenger has problems when you declare validations of more than one attribute in a line:

validates :name, :message, :presence => true

That's because this line creates a raw_filter with more than one attribute in attributes filter:

Model.send(:_validate_callbacks)
=> [#<ActiveSupport::Callbacks::Callback:0xa350da4 @klass=Model(...), ... , @raw_filter=#<ActiveModel::Validations::PresenceValidator:0x9da7470 @attributes=[:name, :message], @options={}>, @filter="_callback_before_75", @compiled_options="true", @callback_id=76>]

We have to delete the desired attribute from that array and reject the callbacks without attributes

Dummy.class_eval do

  _validators.reject!{ |key, _| key == :field }

  _validate_callbacks.each do |callback|
    callback.raw_filter.attributes.delete :field
  end

  _validate_callbacks.reject! do |callback|
    callback.raw_filter.attributes.empty? || 
      callback.raw_filter.attributes == [:field]
  end
end

I have this working on a Rails 3.2.11 app.

3

For rails 4.2 (~ 5.0) it can be used the following module with a method:

module ValidationCancel
   def cancel_validates *attributes
      attributes.select {|v| Symbol === v }.each do |attr|
         self._validators.delete( attr )

         self._validate_callbacks.select do |callback|
            callback.raw_filter.try( :attributes ) == [ attr ] ;end
         .each do |vc|
            self._validate_callbacks.delete( vc ) ;end ;end ;end ;end

Note: Since the filtern can be a symbol of an association, or a specific validator, so we have to use #try.

Then we can use rails-friendly form in a class declaration:

class Dummy
   extend ValidationCancel
   cancel_validates :field ;end

Note: since removal of the validator is affecting to the whole class and its descendants globally, it is not recommended to use it to remove validations in such way, instead add if clause for the specific rule as follows:

module ValidationCancel
   def cancel_validates *attributes
      this = self
      attributes.select {|v| Symbol === v }.each do |attr|
         self._validate_callbacks.select do |callback|
            callback.raw_filter.try( :attributes ) == [ attr ] ;end
         .each do |vc|
            ifs = vc.instance_variable_get( :@if )
            ifs << proc { ! self.is_a?( this ) } ;end ;end ;end ;end

This restricts execution of the validation callback for the specified class and its descendants.

2

If you doesn't want to make any changes in Parent class then first clear all validations in child class and copy all required validation from parent class to child class

  class Dummy < ActiveRecord::Base
      validates :property, presence: true
      validates :value, length: { maximum: 255 }
  end

And override it in child class

Dummy.class_eval do    
  clear_validators!
  validates :property, presence: true
end
1

If you really want to do this then here would be a good place to start digging: https://github.com/rails/rails/blob/ed7614aa7de2eaeba16c9af11cf09b4fd7ed6819/activemodel/lib/active_model/validations/validates.rb#L82

However, to be honest, inside of ActiveModel is not where I'd be poking with a stick.

11
  • 1
    I don't want to monkey patch more than I need, so changing anything in the ActiveModel is not an option for me, really.
    – mdrozdziel
    Sep 25, 2011 at 20:39
  • I never said that. But if you want to work out what adding a validation does to the model (and thus have any hope of reversing it) you'll need to start by reading this file.
    – thomasfedb
    Sep 25, 2011 at 23:29
  • I would rather avoid digging up the solution in the Rails code, because there is a great chance of finding very wrong solution. After all, the reason for posting this question is hope for a quick and semi-clean solution. Worst case scenario for me is reimplementing the whole model in my code.
    – mdrozdziel
    Sep 26, 2011 at 9:04
  • if you're looking for something that's "quick" or "clean" don't look here. If you read the source code carefully you should find a solution. But as per the advice in the question comments, just not doing this at all would seem your best bet.
    – thomasfedb
    Sep 26, 2011 at 9:07
  • 1
    Thanks for your input, but it is useless. Pretty much every question on StackOverflow can be answerd by "If you read the source code carefully you should find a solution."
    – mdrozdziel
    Sep 26, 2011 at 17:15
1

If you can edit the constraint on the original model to put an :if => :some_function on it, you can easily change the behavior of the function it calls to return false. I tested this and it works pretty easily:

class Foo < ActiveRecord::Base

  validates :field, :presence => true, :if => :stuff


  attr_accessor :field

  def stuff
      return true;
  end

end

and then somewhere else:

Foo.class_eval {
  def stuff
    false
  end
}
1
  • 2
    This solution requires the original model to be altered. This could be a way to go, if one would design the classes from scratch. In this particular question however, there is no such conditional validation. What I need is to simply remove one particular validation defined more-less as specified in the question.
    – mdrozdziel
    Oct 5, 2011 at 8:43
1

Why not use @dummy.save_without_validation method to skip validations altogether? I prefer do something like this:

if @dummy.valid?
  @dummy.save # no problem saving a valid record
else
  if @dummy.errors.size == 1 and @dummy.errors.on(:field)
    # skip validations b/c we have exactly one error and it is the validation that we want to skip
    @dummy.save_without_validation 
  end
end

You could put this code in your model or in the controller, depending on your needs.

1

In Rails 4.1,

I was able to do _validate_callbacks.clear. In my case, I wanted all the validations for a gem removed, so I could create my own. I did this in a module that was patched into the class.

Module #Name
   extend ActiveSupport::Concern
   included do
        _validate_callbacks.clear
        #add your own validations now
   end
end
1

Wanted to add that, if you're trying to clear validations on a instance of your Model (not the entire model class), don't do my_dummy._validate_callbacks.clear, as that will clear validations on every instance (and future instance) of your Dummy model class.

For just the instance (and if you wanted to reinstate the validations later), try the following:

  1. Create a copy of the validate callbacks (if you want to reinstate later): my_dummy_validate_callbacks = my_dummy._validate_callbacks.clone

  2. Set the validate callbacks on your instance to empty: my_dummy._validate_callbacks = {}

  3. Do what you want on my_dummy validation free!

  4. Reinstate the callbacks: my_dummy._validate_callbacks = my_dummy_validate_callbacks

0

I'd have to look more into the code and help, but I'm thining it might be possible to inspect the list of validators of the class, and then modify the entry for the validation you want to change to add in an :if => :some_function conditional to it.

You'll need to do it only once for production (so it can be put inside an initializer, but for development you'll need to put it in the model, or somewhere else that will get loaded each time the corresponding model is (perhaps an observer?).

(I'll edit the answer with more information as I come to research it.)

2
  • It's not so easy. If you define more fields in one validates call, then you have one PresenceValidator with attributes listed in attributes field. You can only add one condition to the validator, so in this case it would be all or nothing. So in order to introduce conditional validation one has to remove the field from the original validator, and define another one. I know I haven't pointed that out in the original question, but actually this is the case in my code. Besides - hacking the validation is not so trivial. There are more then 1 place you have to look into (see aVenger's answer).
    – mdrozdziel
    Oct 11, 2011 at 6:52
  • The simplest way would be to create a proxy method to act as the conditional in the validator, that would call both the existing conditional and your new conditional. Most likely you'd want to use AND to merge the conditions. Since this is Rails I would have thought the simplest thing to do was to clone the gem's repository, make your required changes to the library, and point bundler to use your local copy. You then have the power to keep it updated to the original version and you've got your own changes. Oct 12, 2011 at 23:57
0

Every Rails validator, pre-defined or custom, is an object, and is expected to respond to #validate(record) method. You can monkey patch or stub this method.

# MyModel.validators_on(:attr1, :attr2, ...) is also useful
validator = MyModel.validators.detect do |v|
  validator_i_am_looking_for?(v)
end

def validator.validate(*_)
  true
end

# In RSpec you can also consider:
allow(validator).to receive(:validate).and_return(true)

Tested in Rails 5.1.

Don't do this unless you understand what you're doing ;)

0

This does not directly answer the question but here's an option you should consider in such a situation: instead of disabling validation, you could set the required fields in a before_validation hook.

Since you don't need those required fields, set them with some dummy data that satisfies the validation and forget about them.

No ugly monkey patching.

-2

Assuming the original implementation of Dummy is defined in an engine there is a nasty hack that will do what you want. Define Dummy in your application to keep the original implementation of Dummy from being auto-loaded. Then load the source to Dummy and remove the line that does the validation. Eval the modified source.

Put the following in your app/models/dummy.rb

class Dummy < ActiveRecord::Base
end

# Replace DummyPlugin with name of engine
engine = Rails::Application::Railties.engines.find { |e| e.class == DummyPlugin::Engine }
dummy_source = File.read File.join(engine.config.root, "app", "models", "dummy.rb")
dummy_source = dummy_source.gsub(/validates :field, :presence => true.*/, "")
eval dummy_source

If it is regular gem instead of an engine the same concept would apply, just would need to load the source for Dummy from the gem root instead of the engine root.

1
  • I'll leave this answer as record of what didn't work, but... As it turns out, this works in development, but not in production. Apparently load order is different, and the engine model gets loaded regardless. Jul 11, 2012 at 2:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.