跳过Model中的某些验证方法

时间:2012-01-16 14:54:26

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我正在使用 Rails v2.3

如果我有模型

class car < ActiveRecord::Base

  validate :method_1, :method_2, :method_3

  ...
  # custom validation methods
  def method_1
    ...
  end

  def method_2
    ...
  end

  def method_3
    ...
  end
end

如上所述,我有 3个自定义验证方法,我将它们用于模型验证。

如果我在此模型类中有另一个方法,它保存模型的新实例,如下所示:

# "flag" here is NOT a DB based attribute
def save_special_car flag
   new_car=Car.new(...)

   new_car.save #how to skip validation method_2 if flag==true
end

我想在此特定方法中跳过method_2验证以保存新车,如何跳过某种验证方法?

4 个答案:

答案 0 :(得分:54)

将您的模型更新为此

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

然后在您的控制器中输入:

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

如果您在控制器中通过params变量获得:flag,则可以使用

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

答案 1 :(得分:12)

条件验证的基本用法是:

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

查看文档了解更多详情。

将其调整到您的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

答案 2 :(得分:0)

在验证中使用块,例如:

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

答案 3 :(得分:-2)

根据天气标志为false,请使用方法save(false)跳过验证。