Multiple Validations Grouped By A Condition In Rails

Posted by Weston Ganger

Sometimes you need to apply a if or unless condition to many validations at once. Well heres how to do it in Rails


class Post < ActiveRecord::Base
  with_options if: :is_admin? do |admin|
    admin.validates :password, length: { minimum: 28 }
    admin.validates :authorization_number, presence: true
  end
end

The same rules apply to the if as with other validations, therefore it can be used in one of three ways


if: :is_admin?
if: "is_admin?"
if: Proc.new {|x| x.is_admin?}

Article Topic:Software Development - Rails

Date:March 18, 2015

Recommended Posts