item.rb
我有一个枚举。enum type: { only_rental: 0, rental_buy: 1, only_one: 2 }
现在,我想,如果类型=”only_one”, “rentry_by”,则 price
会是> 0,反之亦然,如果是 “only_rental then = 0。
validates :price, allow_nil: true, numericality: {
only_integer: true,
greater_than: 0,
less_than: 1000000,
}
validates :price, if: proc { !only_rental? }
我尝试了以下方法,但我似乎没有工作。
解决方案:
我喜欢用 validates
并把你这样的逻辑放入 validate
方法。
validates :price, allow_nil: true, numericality: { only_integer: true, less_than: 1000000 }
validate :price_amount
def price_amount
if only_rental?
price.zero?
else
price.positive?
end
end
你也可以使用Rails的 with_options
:
with_options allow_nil: true, numericality: { only_integer: true, less_than: 1000000 } do
validates :price, numericality: { greater_than: 0 }, unless: :only_rental?
validates :price, numericality: { in: [0] }, if: :only_rental?
end
本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/1699.html