所以我想知道我们是否可以有条件 allow_nil 选项来验证 Rails 模型。
我想要做的是能够根据一些逻辑(一些其他属性)allow_nil
所以我有一个可以保存为草稿的产品模型。当保存为草稿时,价格可以为零,但当不是草稿时,保存的价格应该是数字。我怎样才能做到这一点。以下似乎不起作用。它适用于草稿案例,但即使状态不是草稿也允许 nil。
class Product<ActiveRecord::Base
attr_accessible :status, price
validates_numericality_of :price, allow_nil: :draft?
def draft?
self.status == "draft"
end
end
查看 rails 文档,我似乎没有将方法传递给 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
还有其他方法可以让它工作吗?
谢谢
最佳答案
您可以使用 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
关于ruby-on-rails - Rails 模型验证条件 allow_nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922154/