Ruby on Rails Conditional validation

Example

Sometimes you may need to validate record only under certain conditions.

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

  def admin?
    conditional here that returns boolean value
  end
end

If you conditional is really small, you can use a Proc:

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

For negative conditional you can use unless:

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

You can also pass a string, which will be executed via instance_eval:

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