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?
A:if
B:unless
C:only_if
D:when
✗ 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?
AValidates email presence only if user is not admin
BValidates email presence only if user is admin
CAlways validates email presence
DNever validates email presence
✗ 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?
C. Using method call instead of symbol for if condition
D. numericality should be a method, not an option
Solution
Step 1: Check syntax for conditional validation if option
The if: 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 C
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?