Rails的模型验证条件allow_nil? [英] Rails Model Validation Conditional allow_nil?
问题描述
所以我在想,如果我们能有一个铁轨模型验证条件allow_nil选项。
So I was wondering if we can have a conditional allow_nil option for a validation on a rails model.
我想这样做是为了能够根据一些逻辑allow_nil(其他属性)
What I would like to do is to be able to allow_nil depending upon some logic(some other attribute)
所以,我有可以保存为草稿产品模型。当被保存为草稿的价格可以是零,但不是选秀保存的价格应该是数值。我怎样才能做到这一点。下面似乎不工作。它适用于案件草案,但允许零,即使状态不起草。
So I have a product model which can be saved as draft. and when being saved as draft the price can be nil, but when not a draft save the price should be numerical. how can I achieve this. The following doesn't seem to work. It works for draft case but allows nil even when status isn't draft.
class Product<ActiveRecord::Base
attr_accessible :status, price
validates_numericality_of :price, allow_nil: :draft?
def draft?
self.status == "draft"
end
end
看着铁轨文档我看起来像没有通过一个方法allow_nil的选择吗?
Looking at rails docs I looks like there isn't an option to pass a method to allow_nil?
一种可能的解决方案是做单独的验证对于两种情况
One possible solution is to do separate validations for both cases
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
任何其他的方式来得到这个工作?
Any other ways to get this working ?
感谢
推荐答案
您可以使用如果
和除非
来请执行下列操作
You can use if
and unless
to do the following
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个验证设置,一个适用于当草案? ==真
,这将使尼尔斯,和一个其中草案? ==假
这不会让尼尔斯
With the above, you will have 2 validations set up, one that applies when draft? == true
, which will allow nils, and one where draft? == false
which will not allow nils
这篇关于Rails的模型验证条件allow_nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!