How to remove validation using instance_eval clause in Rails?

后端 未结 18 2079
情话喂你
情话喂你 2021-02-01 02:11

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

class Du         


        
18条回答
  •  不要未来只要你来
    2021-02-01 02:38

    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
    }
    

提交回复
热议问题