Intridea Development Blog
Quick Tip: Readable Conditional Validations in Rails
This is something that many may already use as a best practice, but if not it’s something simple and convenient to add to your repertoire. Sometimes you may have a model that requires additional information if a certain condition is met. For example, I may require a user to add more information about themselves if they wish to be listed publicly, whereas I would not if they do not wish to be listed. By combining ActiveSupport’s Object#with_options and ActiveRecord’s conditional validations, we can implement this behavior in a straightforward and readable manner (assuming here that there is a boolean field called “listed” in the database that is exposed as a checkbox or similar to the user):
class User < ActiveRecord::Base
# Our standard validations
validates_presence_of :login
validates_uniqueness_of :login
# Validations for listed users
with_options :if => :listed? do |l|
l.validates_presence_of :email
l.validates_length_of :description, :minimum => 100
end
end
It’s a simple technique that piggybacks off of Rails’s automatic construction of existence query methods (in this case, listed?) for fields in the database combined with the mapping power of with_options and standard conditional validations.
The Intridea Blogs
Blog Archive
- January 2010 (1)
- December 2009 (1)
- November 2009 (2)
- October 2009 (1)
- September 2009 (2)
- August 2009 (2)
- July 2009 (2)
- June 2009 (2)
- May 2009 (1)
- April 2009 (3)
- March 2009 (8)
- February 2009 (9)
- January 2009 (2)
- December 2008 (1)
- November 2008 (1)
- October 2008 (2)
- July 2008 (5)
- June 2008 (8)
- April 2008 (2)
- March 2008 (1)
- February 2008 (4)
- January 2008 (4)
- December 2007 (3)
- November 2007 (3)
- October 2007 (4)
- September 2007 (2)
- August 2007 (3)
Michael Bleigh