跳过Model中的某些验证方法

Lee*_*fin 31 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
Run Code Online (Sandbox Code Playgroud)

如您所见,我有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
Run Code Online (Sandbox Code Playgroud)

我想跳过method_2这种保存新车的特定方法的验证,如何跳过某些验证方法?

shi*_*ime 57

将模型更新为此

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
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中放:

def save_special_car
   new_car=Car.new(skip_method_2: true)
   new_car.save
end
Run Code Online (Sandbox Code Playgroud)

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

def save_special_car
   new_car=Car.new(skip_method_2: params[:flag].present?)
   new_car.save
end
Run Code Online (Sandbox Code Playgroud)


Mic*_*jbe 13

条件验证的基本用法是:

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
Run Code Online (Sandbox Code Playgroud)

查看文档以获取更多详细信息.

将其调整为您的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
Run Code Online (Sandbox Code Playgroud)

  • 实际上,标志不是基于数据库的属性...那么...还有其他方法吗? (2认同)