Validations, :if and Proc.new

written by justin on September 17th, 2007 @ 03:44 PM

I learned something new today about dealing with conditional validations in Ruby on Rails. I have an Active Record (AR) class that has multiple states during its life cycle. It is initially created with a bare minimum of information. Essentially the record is created to be a place holder for future activity relating to an application that may or may not be returned.

I set up my initial validations for the information that would be available when the application is given out. That is pretty basic stuff and I've done it a number of times. It worked as expected, so I moved on to the next step.

When the application is returned we need to find that record, and update it with some additional information, and this new information needs to be validated as well. I have multiple steps of updates, so I couldn't really use the :on => (created|updated) parameter.

My first thought was that I'd have to put that validation into the Controller. I immediately got a bad taste in my mouth at the thought of what that would look like. I thought to myself, "self, we'd better check Agile Web Development with Rails" before we do anything.

What I found was the :if parameter of the Validation Helpers in Rails. The :if parameter causes the validation to be run only if the boolean returned is true. The :if can be either:

  • a method call using a Symbol, which is passed the AR object as the parameter i.e. :if => :some_method_name
  • a string, which is evaluated i.e. :if => %q{"a small sentence".length}
  • a proc object, which is called with the AR object as the parameter i.e. :if => Proc.new {|u| u.classify}
I set a flag on my object telling it what step I'm on and then my conditional validations queue on that variable and the correct information is validated at the correct time.

Post a comment