Validating numericality based on related attribute value?


#1

I have a price attribute in my model which I need to validate as a
positive number if the attribute price_terms.requires_value is equal to
‘Y’, otherwise price can be blank or zero. Price_terms is a select list
which my model table belongs_to.

How do I do this? - I tried doing this:

validates_numericality_of :price, :if =>
self.price_term.requires_value.upcase == ‘Y’

But that doesn’t work…

Thanks in advance,

Matt.


#2

Try this:

validates_numericality_of :price, :if => Proc.new { |r|
r.price_term.requires_value.upcase == ‘Y’ }

-Jonathan.