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 


Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts