Conditional validations let you check data only when certain rules apply. This helps keep your app flexible and accurate.
Conditional validations in Ruby on Rails
validates :field_name, presence: true, if: :condition_method # or validates :field_name, presence: true, unless: :condition_method # condition_method is a method that returns true or false
The if option runs validation only when the method returns true.
The unless option runs validation only when the method returns false.
validates :email, presence: true, if: :email_required? def email_required? user_signed_in? end
validates :age, numericality: { greater_than: 18 }, unless: :admin?
def admin?
role == 'admin'
endvalidates :password, presence: true, if: -> { new_record? } # Uses a lambda to validate password only when creating a new record.
This User model requires phone_number only if contact_method is 'phone'. The example shows validation fails when phone_number is empty but contact_method is 'phone'. It passes when contact_method is 'email' even if phone_number is empty.
class User < ApplicationRecord validates :phone_number, presence: true, if: :contact_by_phone? def contact_by_phone? contact_method == 'phone' end end # Example usage: user1 = User.new(contact_method: 'phone', phone_number: '') user2 = User.new(contact_method: 'email', phone_number: '') puts user1.valid? # false because phone_number is required puts user2.valid? # true because phone_number not required
Use simple method names for conditions to keep code readable.
Lambdas can be used for inline conditions without defining separate methods.
Conditional validations help avoid unnecessary errors and improve user experience.
Conditional validations run only when specific conditions are met.
Use if or unless with methods or lambdas.
This makes your validations flexible and context-aware.