[Ruby on Rails] with_options を使ってバリデーションをグルーピング

Tadashi Shigeoka ·  Tue, January 22, 2013

Ruby on Rails で、ある条件の時だけバリデーションを掛けたいときは with_options を使えばグルーピングできて素敵です。

Ruby on Rails Guides: Active Record Validations and Callbacks はてなブックマーク - Ruby on Rails Guides: Active Record Validations and Callbacks

paramがなければModelのValidationをskipすれば良いじゃない #Ruby #Rails - Qiita はてなブックマーク - paramがなければModelのValidationをskipすれば良いじゃない #Ruby #Rails - Qiita

5.4 Grouping conditional validations Sometimes it is useful to have multiple validations use one condition, it can be easily achieved using with_options.
class User < ActiveRecord::Base
  with_options :if => :is_admin? do |admin|
    admin.validates :password, :length => { :minimum => 10 }
    admin.validates :email, :presence => true
  end
end

All validations inside of with_options block will have automatically passed the condition :if => :is_admin?