How to remove validation using instance_eval clause in Rails?

后端 未结 18 1844
情话喂你
情话喂你 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:50

    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)
    => [#, @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.

提交回复
热议问题