Bird
Raised Fist0
Ruby on Railsframework~10 mins

Conditional validations in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Conditional validations
Start: Model instance created
↓
Check validation condition?
No→Skip validation
Yes↓
Run validation rule
↓
Validation passes?
No→Add error message
Yes↓
End
Rails checks if a condition is true before running a validation. If true, it validates; if false, it skips.
Execution Sample
Ruby on Rails
class User < ApplicationRecord
  validates :email, presence: true, if: :email_required?

  def email_required?
    admin?
  end
end
This code validates email presence only if the user is an admin.
Execution Table
StepUser.admin?Condition (if: email_required?)Validation run?Validation resultErrors added
1truetrueYesPassNo
2falsefalseNoSkippedNo
💡 Validation stops after checking condition; if false, validation is skipped.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
admin?niltruefalsefalse
email_required?niltruefalsefalse
errors[:email][][][][]
Key Moments - 2 Insights
Why does the validation sometimes not run even if the attribute is empty?
Because the condition method (email_required?) returned false, so Rails skipped the validation as shown in execution_table row 2.
What happens if the condition method returns true but the attribute is valid?
Validation runs and passes, so no errors are added, as shown in execution_table row 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the validation result when admin? is false?
AValidation passes
BValidation is skipped
CValidation fails
DError is added
💡 Hint
Check row 2 under 'Validation result' in the execution_table.
At which step does Rails add an error message?
ANeither step
BStep 2
CStep 1
DBoth steps
💡 Hint
Look at the 'Errors added' column in the execution_table for both steps.
If admin? always returns true, how does the validation behave?
AValidation runs only if email is present
BValidation never runs
CValidation always runs
DValidation runs only if email is absent
💡 Hint
Refer to the 'Condition' and 'Validation run?' columns in the execution_table.
Concept Snapshot
Rails conditional validations run only if a condition is true.
Use :if or :unless with a method or proc.
If condition false, validation skips.
Errors added only if validation runs and fails.
Example: validates :email, presence: true, if: :admin?
This keeps validations flexible and efficient.
Full Transcript
In Rails, conditional validations let you run validations only when certain conditions are met. For example, you can validate an email only if the user is an admin. The flow starts when a model instance is created. Rails checks the condition method, like admin?. If it returns true, Rails runs the validation. If the validation passes, no errors are added. If it fails, errors are added to the model. If the condition returns false, Rails skips the validation entirely. This helps avoid unnecessary checks and keeps your model logic clean. The example code shows a User model validating email presence only if admin? returns true. The execution table shows two cases: when admin? is true, validation runs and passes; when false, validation is skipped. Variables like admin? and email_required? change accordingly during execution. Common confusions include why validations sometimes don't run (because condition is false) and when errors get added (only if validation runs and fails). The quiz questions help reinforce understanding by asking about validation results and error additions based on the execution table. Overall, conditional validations make your Rails models smarter and more efficient by running checks only when needed.

Practice

(1/5)
1. What does a conditional validation in Rails do?
easy
A. Runs validation only when a specific condition is true
B. Runs validation on every save regardless of conditions
C. Disables all validations temporarily
D. Automatically fixes invalid data

Solution

  1. Step 1: Understand the purpose of conditional validations

    Conditional validations allow validations to run only if certain conditions are met, making them flexible.
  2. 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.
  3. Final Answer:

    Runs validation only when a specific condition is true -> Option A
  4. Quick Check:

    Conditional validation = run if condition true [OK]
Hint: Conditional validations run only when conditions are true [OK]
Common Mistakes:
  • Thinking validations always run on every save
  • Confusing conditional validations with disabling validations
  • Believing validations fix data automatically
2. Which of the following is the correct syntax to add a conditional validation using if with a method named active??
easy
A. validates :name, presence: true if :active?
B. validates :name, presence: true, if: :active?
C. validates :name, presence: true, if active?
D. validates :name, presence: true, if => :active?

Solution

  1. Step 1: Recall correct syntax for conditional validations

    Rails uses a hash key if: followed by a symbol or lambda for conditions.
  2. Step 2: Match options with correct syntax

    validates :name, presence: true, if: :active? correctly uses if: :active?. Others have syntax errors or missing commas.
  3. Final Answer:

    validates :name, presence: true, if: :active? -> Option B
  4. Quick Check:

    Use if: :method_name for conditional validation [OK]
Hint: Use if: :method_name with a comma for conditional validations [OK]
Common Mistakes:
  • Omitting comma before if
  • Using if without colon or symbol
  • Using wrong hash rocket syntax
3. Given this model code:
class User < ApplicationRecord
  validates :email, presence: true, unless: :guest?
  def guest?
    role == 'guest'
  end
end

What happens when you save a User with role = 'guest' and email = nil?
medium
A. Validation fails because role is not checked
B. Validation fails because email is missing
C. Raises an error due to missing email
D. Validation passes because guest users skip email validation

Solution

  1. Step 1: Understand the conditional validation with unless

    The validation runs unless the guest? method returns true. If user is guest, validation is skipped.
  2. Step 2: Apply to given user data

    User has role 'guest', so guest? returns true, skipping email presence validation. So saving passes despite missing email.
  3. Final Answer:

    Validation passes because guest users skip email validation -> Option D
  4. Quick Check:

    unless: :guest? skips validation if guest? true [OK]
Hint: unless skips validation when condition method returns true [OK]
Common Mistakes:
  • Assuming validation always runs regardless of unless
  • Confusing unless with if
  • Expecting error instead of skip
4. Identify the error in this validation code:
validates :age, numericality: true, if: user.adult?
medium
A. No error, code is correct
B. Missing comma after numericality: true
C. Using method call instead of symbol for if condition
D. numericality should be a method, not an option

Solution

  1. Step 1: Check syntax for conditional validation if option

    The if: option expects a symbol or lambda, not a method call.
  2. Step 2: Analyze given code

    Here, user.adult? is a method call, which is invalid syntax in validation options.
  3. Final Answer:

    Using method call instead of symbol for if condition -> Option C
  4. Quick Check:

    Use symbol (:method_name), not method call, for if condition [OK]
Hint: Use :method_name symbol, not method call, in if condition [OK]
Common Mistakes:
  • Calling method instead of passing symbol
  • Confusing method call with symbol
  • Ignoring syntax errors in validation options
5. You want to validate presence of 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?
hard
A. validates :phone_number, presence: true, if: -> { admin? || active? }
B. validates :phone_number, presence: true, if: :admin? && :active?
C. validates :phone_number, presence: true, if: [:admin?, :active?]
D. validates :phone_number, presence: true, if: admin? or active?

Solution

  1. Step 1: Understand combining conditions in validations

    To combine multiple conditions, use a lambda with logical operators inside the if: option.
  2. Step 2: Evaluate each option's syntax

    validates :phone_number, presence: true, if: -> { admin? || active? } uses a lambda with admin? || active?, which is correct. Others misuse symbols or syntax.
  3. Final Answer:

    validates :phone_number, presence: true, if: -> { admin? || active? } -> Option A
  4. Quick Check:

    Use lambda with || to combine conditions in if [OK]
Hint: Use lambda with || to combine multiple conditions in if [OK]
Common Mistakes:
  • Using && or || with symbols directly
  • Passing array of symbols instead of lambda
  • Writing invalid Ruby syntax in if option
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard