Conditional validation

suggest change

Sometimes a record should be validated only under certain conditions.

class User < ApplicationRecord
  validates :name, presence: true, if: :admin?

  def admin?
    # return true or false
  end
end

If the condition is small, use a proc:

class User < ApplicationRecord
  validates :first_name, presence: true, if: Proc.new { |user| user.last_name.blank? }
end

For the opposite condition, use unless:

class User < ApplicationRecord
  validates :first_name, presence: true, unless: Proc.new { |user| user.last_name.present? }
end

Older Rails versions also accept a string, which is run with instance_eval. Prefer a symbol or a proc; string conditions are deprecated:

class User < ApplicationRecord
  validates :first_name, presence: true, if: 'last_name.blank?'
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents