Recall & Review
beginner
What is a conditional validation in Rails?
A conditional validation runs only when a specific condition is true. It helps check data only in certain cases, like validating a field only if another field has a certain value.
Click to reveal answer
beginner
How do you use
:if option in Rails validations?You add
:if with a method name, proc, or lambda that returns true or false. The validation runs only if it returns true.Click to reveal answer
beginner
Example: Validate presence of
nickname only if user_type is 'guest'. How to write this?Use
validates :nickname, presence: true, if: -> { user_type == 'guest' }. This means nickname must be present only when user_type equals 'guest'.Click to reveal answer
intermediate
What is the difference between
:if and :unless in Rails validations?:if runs validation when condition is true. :unless runs validation when condition is false. They are opposites.Click to reveal answer
intermediate
Can you use multiple conditions in Rails validations? How?
Yes, you can combine
:if and :unless or use methods that check multiple conditions. The validation runs only if all conditions are met.Click to reveal answer
Which option runs a validation only when a condition is true?
✗ Incorrect
The :if option runs the validation only if the given condition returns true.
What does this validation do?
validates :email, presence: true, unless: :admin?✗ Incorrect
The :unless option skips validation if the method admin? returns true, so it validates only if user is not admin.
How can you write a conditional validation using a method?
✗ Incorrect
You pass the method name as a symbol to :if, like if: :method_name, so Rails calls it to check the condition.
What type of object can you use with :if for conditional validation?
✗ Incorrect
:if accepts symbols (method names), procs, or lambdas that return true or false.
If you want a validation to run only when two conditions are true, what should you do?
✗ Incorrect
Combine the conditions inside one method or lambda and pass it to :if so validation runs only if all conditions are true.
Explain how to use conditional validations in Rails with examples.
Think about when you want validations to run only sometimes.
You got /3 concepts.
Describe the difference between :if and :unless in Rails validations and when to use each.
They are opposites controlling when validations run.
You got /3 concepts.