How to remove validation using instance_eval clause in Rails?

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

    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.

提交回复
热议问题