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.
Practice
Solution
Step 1: Understand the purpose of conditional validations
Conditional validations allow validations to run only if certain conditions are met, making them flexible.Step 2: Compare options with this purpose
Only Runs validation only when a specific condition is true describes running validation based on a condition, matching the concept.Final Answer:
Runs validation only when a specific condition is true -> Option AQuick Check:
Conditional validation = run if condition true [OK]
- Thinking validations always run on every save
- Confusing conditional validations with disabling validations
- Believing validations fix data automatically
if with a method named active??Solution
Step 1: Recall correct syntax for conditional validations
Rails uses a hash keyif:followed by a symbol or lambda for conditions.Step 2: Match options with correct syntax
validates :name, presence: true, if: :active? correctly usesif: :active?. Others have syntax errors or missing commas.Final Answer:
validates :name, presence: true, if: :active? -> Option BQuick Check:
Use if: :method_name for conditional validation [OK]
- Omitting comma before if
- Using if without colon or symbol
- Using wrong hash rocket syntax
class User < ApplicationRecord
validates :email, presence: true, unless: :guest?
def guest?
role == 'guest'
end
endWhat happens when you save a User with
role = 'guest' and email = nil?Solution
Step 1: Understand the conditional validation with unless
The validation runs unless theguest?method returns true. If user is guest, validation is skipped.Step 2: Apply to given user data
User has role 'guest', soguest?returns true, skipping email presence validation. So saving passes despite missing email.Final Answer:
Validation passes because guest users skip email validation -> Option DQuick Check:
unless: :guest? skips validation if guest? true [OK]
- Assuming validation always runs regardless of unless
- Confusing unless with if
- Expecting error instead of skip
validates :age, numericality: true, if: user.adult?
Solution
Step 1: Check syntax for conditional validation if option
Theif:option expects a symbol or lambda, not a method call.Step 2: Analyze given code
Here,user.adult?is a method call, which is invalid syntax in validation options.Final Answer:
Using method call instead of symbol for if condition -> Option CQuick Check:
Use symbol (:method_name), not method call, for if condition [OK]
- Calling method instead of passing symbol
- Confusing method call with symbol
- Ignoring syntax errors 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?Solution
Step 1: Understand combining conditions in validations
To combine multiple conditions, use a lambda with logical operators inside theif:option.Step 2: Evaluate each option's syntax
validates :phone_number, presence: true, if: -> { admin? || active? } uses a lambda withadmin? || active?, which is correct. Others misuse symbols or syntax.Final Answer:
validates :phone_number, presence: true, if: -> { admin? || active? } -> Option AQuick Check:
Use lambda with || to combine conditions in if [OK]
- Using && or || with symbols directly
- Passing array of symbols instead of lambda
- Writing invalid Ruby syntax in if option
Ready to prove it?
Pass the test and this pattern moves unknown
