Conditional validation
suggest changeSometimes 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents