How to remove validation using instance_eval clause in Rails?

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

    Why not use @dummy.save_without_validation method to skip validations altogether? I prefer do something like this:

    if @dummy.valid?
      @dummy.save # no problem saving a valid record
    else
      if @dummy.errors.size == 1 and @dummy.errors.on(:field)
        # skip validations b/c we have exactly one error and it is the validation that we want to skip
        @dummy.save_without_validation 
      end
    end
    

    You could put this code in your model or in the controller, depending on your needs.

提交回复
热议问题