How to remove validation using instance_eval clause in Rails?

后端 未结 18 1841
情话喂你
情话喂你 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 03:01

    I think this is the most actual solution at this moment (I'm using rails 4.1.6):

    # Common ninja
    class Ninja < ActiveRecord::Base
      validates :name, :martial_art, presence: true
    end
    
    # Wow! He has no martial skills
    Ninja.class_eval do
      _validators[:martial_art]
        .find { |v| v.is_a? ActiveRecord::Validations::PresenceValidator }
        .attributes
        .delete(:martial_art)
    end
    

提交回复
热议问题