in Railscasts, Uncategorized

Railscast 042 With Options

class User < ActiveRecord::Base
  with_options if: :should_validate_password? do |user|
    user.validates_presence_of :password
    user.format_of :password, with: /^[^\s]+$/

  attr_accessor :updating_password

  def should_validate_password?
    updating_password || new_record?

class Account < ActiveRecord::Baase
  with_options dependent: :destroy do |acc|
    acc.has_many :customers
    acc.has_many :products
    acc.has_many :invoices
    acc.has_many :expenses

This is a convenient method to be aware of. When there are numerous records that have the same options, then using with_options could clean up the code and it more DRY.

The with_options() method accepts the options as the first argument, then it accepts a block for the model class. This argument is the object used to call the validations on. In the case of user, user.validates_presence_of :password does the normal presence validation, but adds the benefit of using the with_options() method.

Further Reading