Bird
Raised Fist0
Ruby on Railsframework~20 mins

Conditional validations in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Conditional Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when conditional validation is triggered?
Consider this Rails model snippet:
class User < ApplicationRecord
  validates :email, presence: true, if: :email_required?

  def email_required?
    age >= 18
  end
end

What is the validation behavior when a User is 17 years old and email is blank?
AValidation passes because email presence is only checked if age is 18 or more.
BValidation passes only if email is blank and age is exactly 17.
CValidation fails because age is less than 18 but email is blank.
DValidation fails because email must always be present.
Attempts:
2 left
💡 Hint
Look at the condition method email_required? and when it returns true.
📝 Syntax
intermediate
2:00remaining
Identify the correct syntax for conditional validation using :unless
Which option correctly uses :unless to skip validation when the user is an admin?
class User < ApplicationRecord
  # Validate presence of password unless user is admin
end
Avalidates :password, presence: true, unless: admin?
Bvalidates :password, presence: true, unless: :admin?
Cvalidates :password, presence: true, unless: admin
Dvalidates :password, presence: true, unless: -> { admin? }
Attempts:
2 left
💡 Hint
The :unless option expects a symbol referencing a method name.
🔧 Debug
advanced
2:00remaining
Why does this conditional validation never run?
Given this model:
class Product < ApplicationRecord
  validates :price, numericality: true, if: :on_sale

  def on_sale
    sale == true
  end
end

Why might the price validation never trigger even when sale is true?
AThe method on_sale should be named on_sale? with a question mark.
BThe if option expects a symbol, but :on_sale is a method returning a boolean, so it works fine.
CThe validation needs to use unless instead of if to work correctly.
DThe sale attribute might be a string 'true' instead of boolean true, causing on_sale to return false.
Attempts:
2 left
💡 Hint
Check the data type of the sale attribute and how Ruby compares true with 'true'.
❓ state_output
advanced
2:00remaining
What is the validation error output for this conditional validation?
Consider this model:
class Order < ApplicationRecord
  validates :shipping_address, presence: true, if: -> { delivery_required }

  def delivery_required
    delivery == 'yes'
  end
end

order = Order.new(delivery: 'yes', shipping_address: '')
order.valid?
order.errors.full_messages

What is the output of order.errors.full_messages?
A[] (empty array)
B["Delivery must be yes"]
C["Shipping address can't be blank"]
D["Shipping address is invalid"]
Attempts:
2 left
💡 Hint
The validation runs only if delivery_required returns true.
🧠 Conceptual
expert
3:00remaining
Which conditional validation approach is best for complex logic?
You want to validate an attribute only if multiple conditions are met, including checking user role, time of day, and a feature flag. Which approach is best in Rails?
AUse a single method that returns true or false combining all conditions, then use if: :method_name.
BChain multiple validations each with simple if conditions for each check separately.
CUse a lambda with all conditions inside for the if option.
DUse validates with unless option negating all conditions.
Attempts:
2 left
💡 Hint
Think about maintainability and clarity for complex conditions.

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