简体   繁体   中英

How to validates with proc in rails

item.rb

I have enum: enum type: { only_rental: 0, rental_buy: 1, only_one: 2 }

Now I want that if in case of type = "only_one","rental_by", then price would be> 0 and vice versa if it was "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? }

I tried it as follows but but i don't seem to work

Try

validates :price, allow_nil: true, numericality: {
    only_integer: true,
    greater_than: 0,
    less_than: 1000000,
  }, unless: Proc.new { only_rental? }

you can use lambda syntax for Proc.new { only_rental? } Proc.new { only_rental? } as -> { only_rental? } -> { only_rental? }

I prefer to validate format with validates and put such logic as your into validate methods:

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

also you could use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM