Forum: Ruby on Rails Conditional validates_inclusion_of execution problem

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wes G. (Guest)
on 2007-01-18 02:27
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
Daniel -. (Guest)
on 2007-01-18 02:35
(Received via mailing list)
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
Wes G. (Guest)
on 2007-01-18 02:41
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+/}
This topic is locked and can not be replied to.