skip certain validation method in Model

孤街醉人 提交于 2019-11-27 19:40:37

Update your model to this

class Car < ActiveRecord::Base

  # depending on how you deal with mass-assignment
  # protection in newer Rails versions,
  # you might want to uncomment this line
  # 
  # attr_accessible :skip_method_2

  attr_accessor :skip_method_2 

  validate :method_1, :method_3
  validate :method_2, unless: :skip_method_2

  private # encapsulation is cool, so we are cool

    # custom validation methods
    def method_1
      # ...
    end

    def method_2
      # ...
    end

    def method_3
      # ...
    end
end

Then in your controller put:

def save_special_car
   new_car=Car.new(skip_method_2: true)
   new_car.save
end

If you're getting :flag via params variable in your controller, you can use

def save_special_car
   new_car=Car.new(skip_method_2: params[:flag].present?)
   new_car.save
end

The basic usage of conditional validation is:

class Car < ActiveRecord::Base

  validate :method_1
  validate :method_2, :if => :perform_validation?
  validate :method_3, :unless => :skip_validation?

  def perform_validation?
    # check some condition
  end

  def skip_validation?
    # check some condition
  end

  # ... actual validation methods omitted
end

Check out the docs for more details.

Adjusting it to your screnario:

class Car < ActiveRecord::Base

  validate :method_1, :method_3
  validate :method_2, :unless => :flag?

  attr_accessor :flag

  def flag?
    @flag
  end    

  # ... actual validation methods omitted
end

car = Car.new(...)
car.flag = true
car.save

Use block in your validation something like :

validates_presence_of :your_field, :if =>  lambda{|e| e.your_flag ...your condition}

Depending on weather flag is true of false, use the method save(false) to skip validation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!