[英]Rails Model Validation Conditional allow_nil?
所以我想知道我們是否可以在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
有什么其他方法讓這個工作?
謝謝
您可以使用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
draft? == true
,哪個會允許nils,哪個會選擇draft? == false
draft? == false
,不允許nils
那么你不需要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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.