Rails

Multiple Validations Grouped By A Condition In Rails

Posted by Weston Ganger on March 18, 2015

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?}

Posted in Rails and Tagged with rails active-record ruby validation 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts