Validations with conditions (:if)


#1

Hello all.

I have a users table (it has three columns: name, password, active) and
I want to validate it’s name column only if the active column is set to
true. To do this I use the :if statement in all my validations, but it
doesn’t work. I’ve tried many ways to do this (using Symbols, Proc’s or
methods) and nothing works (using Symbols doesn’t work because the
active column is set always to false, using Proc’s the User class has an
invalid syntax and using a method has the same problem as using a
Symbol).

Can you tell me what I’m doing wrong?

Here is the code:

Using a symbol:
validates_length_of :name, :in => 3…30, :if = :active

Using proc:
validates_length_of :name, :in => 3…30, :if = Proc.new { |user|
user.active == true }

Using a method:
validates_length_of :name, :in => 3…30, :if = is_state_active

self.def is_state_active
Proc.new { |user| user.active == true }
end

I’m using Rails 1.0.

Thanks for your help.