How to remove validation using instance_eval clause in Rails?

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

    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
    

提交回复
热议问题