所以我想知道我们是否可以在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
查看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
有什么其他方法可以让它发挥作用吗?
由于
答案 0 :(得分:7)
您可以使用if
和unless
执行以下操作
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
通过以上操作,您将设置2个验证,一个适用于draft? == true
,适用于nils,另一个draft? == false
不允许使用nils
答案 1 :(得分:0)
那么您不需要allow_nil
,只需使用if
:
class Product < ActiveRecord::Base
attr_accessible :status, price
validates_numericality_of :price, if: -> { (draft? && !price.nil?) || !draft? }
def draft?
self.status == "draft"
end
end