Performance: Conditional validations
Conditional validations affect server-side processing time and can indirectly impact user experience by delaying response time.
validates :email, presence: true, if: :simple_flag?validates :email, presence: true, if: -> { complex_method_call_that_queries_database }| Pattern | Server Processing | Database Queries | Response Delay | Verdict |
|---|---|---|---|---|
| Complex condition with DB query | High | Multiple per validation | Noticeable delay | [X] Bad |
| Simple boolean flag condition | Low | None | Minimal delay | [OK] Good |
if with a method named active??if: followed by a symbol or lambda for conditions.if: :active?. Others have syntax errors or missing commas.class User < ApplicationRecord
validates :email, presence: true, unless: :guest?
def guest?
role == 'guest'
end
endrole = 'guest' and email = nil?guest? method returns true. If user is guest, validation is skipped.guest? returns true, skipping email presence validation. So saving passes despite missing email.validates :age, numericality: true, if: user.adult?
if: option expects a symbol or lambda, not a method call.user.adult? is a method call, which is invalid syntax in validation options.phone_number only if the user is an admin or if the account is active. Which is the correct way to write this conditional validation?if: option.admin? || active?, which is correct. Others misuse symbols or syntax.Pass the test and this pattern moves unknown