How to remove validation using instance_eval clause in Rails?

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

    One solution is to extend validates :

    #no need of instance_eval just open the class
    class Dummy < ActiveRecord::Base
      #validates :field, :presence => true 
    
      def self.validates(*attributes)
        if attributes.first == :field #=> add condition on option if necessary
          return # don't validate
        else
          super(*attributes) #let normal behavior take over
        end
      end
    end
    

    And no that's not monkey-patching but extending or decorating a behavior. Rails 3.1 is built on the idea of "multi- inheritance" with module inclusion, specifically to allow this kind agility.

    update #2

    One caveat is you must load the class with the redefined validates method before the gem containing the call to validates. To do so, require the file in config/application.rb after require "rails/all" as suggested in the railsguides. Something like that :

    require File.expand_path('../boot', __FILE__)
    
    require 'rails/all' # this where rails (including active_record) is loaded
    require File.expand_path('../dummy' __FILE__) #or wherever you want it
    
    #this is where the gems are loaded...
    # the most important is that active_record is loaded before dummy but...
    # not after the gem containing the call to validate :field
    if defined?(Bundler)
      Bundler.require *Rails.groups(:assets => %w(development test))
    end
    

    Hope it works now!

提交回复
热议问题