Conditional validates_inclusion_of execution problem


#1

All,

I have a field that I’m validating with validates_numericality_of on as
well as validates_inclusion_of, like so:

validates_numericality_of :number_of_owners,
:only_integer => true,
:message => ‘must be a whole number’

validates_inclusion_of :number_of_owners,
:in => 1…3,
:message => ‘should be between 1 and 3’,
:if => Proc.new {|x| x.number_of_owners =~ /\d+/}

As you can see, I’m using the :if clause to limit the inclusion
validation to cases where the field actually contains digits.

But the inclusion valiation never runs. Is this because
x.number_of_owners isn’t set yet at the time the :if is evaluated? How
can I defer the inclusion validation until I know that the numericality
has been satisfied?

Thanks,
Wes


#2

On 1/18/07, Wes G. removed_email_address@domain.invalid wrote:

can I defer the inclusion validation until I know that the numericality
has been satisfied?

Wes, I think the problem is that your trying a regexp on an Integer.
Instead you could use

:if => Proc.new{ |x| x.number_of_owners.is_a?(Integer) }

You might consider allowing nil for this as well.

Hope that helps


#3

This seems to work - the attribute is an integer, not a string.

validates_inclusion_of :number_of_owners,
:in => 1…3,
:message => ‘should be between 1 and 3’,
:if => Proc.new {|aqi| aqi.number_of_owners.to_s
=~ /\d+/}