Matthew Law
2006-Jun-07  21:05 UTC
[Rails] Validating numericality based on related attribute value?
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.
Jonathan Viney
2006-Jun-07  23:35 UTC
[Rails] Validating numericality based on related attribute value?
Try this:
validates_numericality_of :price, :if => Proc.new { |r|
r.price_term.requires_value.upcase == ''Y'' }
-Jonathan.
On 6/8/06, Matthew Law <matt@matthewlaw.plus.com>
wrote:> 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.