Posts tagged with: "with_options"

Quick Tip: Readable Conditional Validations in Rails

Mini

by Michael Bleigh

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.

Comment | 

Words we've written view all blog posts »

Featured Article

Intridea at Lonestar Ruby Conference

by Renae Bair on August 18, 2010

For the third straight year in a row, senior-level developers from the Intridea team will be at the Lonestar Ruby Conference, on Thursday, August 26th, teaching students about Ruby. Students attending the Ruby Intrigue class will work with our Director of Mobile Development, Brendan Lim, our Director of Development, Adam Bair, and our Director of Research and Development, Pradeep Elankumaran. Continue reading »

Recent Blog Posts

FlockFeeds Launches From Node Knockout

by Intridea on August 30, 2010

Using NPM with Heroku Node.js

by Michael Bleigh on August 24, 2010

Fixing Common Bundler Problems

by Jerry Cheung on August 23, 2010