agente_secreto
agente_secreto

Reputation: 8079

Rails conditional validation not working

I am trying to do the following:

  validates :price, :presence => true, :if => Proc.new {|p| p.available == true}
  validates :price, :presence => false, :if => Proc.new {|p| p.available == false}

So that if the boolean :available is true, :price must be present, and if it is false, :price must be nil.

But when I test this in the console it doesnt work. Any idea about what am I might be doing wrong?

Upvotes: 1

Views: 1076

Answers (2)

stfcodes
stfcodes

Reputation: 1380

Based on your comment and from what I can understand you have a Product model, and you want to set the price, only if the products available flag is true.

As per other comments, i don't think you can stack validations... And even if it's possible in some way, I don't think it is good UX to have a validation error like "price must not be set if product is unavailable".

My suggestion is to have only the first validation, and silently reject the price if the flag is set to false. First via javascript for good UX (disable the input when the boolean is checked), and secondly inside a callback to be sure no one tampers with the HTML.

The ruby part can go like this:

class Product < ActiveRecord::Base

  validates   :price, presence: true, if: "available?"

  before_save :reject_price, if: "available? == false"

  private

  def reject_price
    self.price = nil
  end
end

Upvotes: 2

Marlin Pierce
Marlin Pierce

Reputation: 10081

Yeah, I'm not sure you can stack validations now. However, you may be able to do what you want from a before_validation.

class Foo
  before_validation :price_matches_available

  def price_matches_available
    available ? price.present? : price.nil?
  end
end

Upvotes: 2

Related Questions