How to remove validation using instance_eval clause in Rails?

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

    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.

提交回复
热议问题