Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Feb 25 ’10

Conditional Validation using with_options to improve readability

When you have a model that requires additional information, if a certain condition is met and you need to validate this attribute, this little trick can help.

Say we have a user model that needs to validate the truck_serial attribute if the user has the role of driver:

class User < ActiveRecord::Base
  has_many :roles

  # Normal Validations 
  validates_presence_of   :user_name
  validates_uniqueness_of :user_name

  with_options :if => :driver? do |driver|
    driver.validates_presence_of :truck_serial
    driver.validates_length_of :truck_serial, :maximum => 30
  end

  def driver?
    roles.any? { |role| role.name == "driver" }
  end 
end  

We are basically combining the ActiveSupport Object#with_options and ActiveRecord’s conditional validation.

This tip was submitted by exceptionz.

97 notes 0 comments

  1. estantres reblogged this from rubyquicktips
  2. exceptionz submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus