Rails模型验证条件allow_nil?

Abi*_*bid 3 validation activerecord ruby-on-rails ruby-on-rails-3

所以我想知道我们是否可以在rails模型上使用条件allow_nil选项进行验证.

我想做的是能够根据一些逻辑(一些其他属性)allow_nil

所以我有一个产品型号可以保存为草稿.当被保存为草案时,价格可以是零,但是当不是草稿时,保存价格应该是数字.我该怎么做到这一点.以下似乎不起作用.它适用于草案,但即使状态不是草案也允许为零.

class Product<ActiveRecord::Base
   attr_accessible :status, price
   validates_numericality_of :price, allow_nil: :draft?

   def draft?
     self.status == "draft"
   end

end
Run Code Online (Sandbox Code Playgroud)

看看rails docs我看起来没有选项将方法传递给allow_nil?

一种可能的解决方案是对两种情况进行单独的验证

 with_options :unless => :draft? do |normal|
    normal.validates_numericality_of :price
 end

 with_options :if => :draft? do |draft|
   draft.validates_numericality_of :price, allow_nil: true
 end
Run Code Online (Sandbox Code Playgroud)

有什么其他方法让这个工作?

谢谢

Dan*_*ain 8

您可以使用ifunless执行以下操作

class Product<ActiveRecord::Base
   attr_accessible :status, price
   validates_numericality_of :price, allow_nil: true, if: :draft?
   validates_numericality_of :price, allow_nil: false, unless: :draft?

   def draft?
     self.status == "draft"
   end

end
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,您将设置2个验证,一个适用于何时draft? == true,将允许nils,以及一个draft? == false不允许nils的验证