0
0
Ruby on Railsframework~5 mins

Conditional validations in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A:if
B:unless
C:only_if
D:when
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
How can you write a conditional validation using a method?
Avalidates :name, presence: true, if: method_name
Bvalidates :name, presence: true, if: method_name()
Cvalidates :name, presence: true, if: 'method_name'
Dvalidates :name, presence: true, if: :method_name
What type of object can you use with :if for conditional validation?
AOnly symbols
BSymbols, procs, or lambdas
COnly strings
DOnly booleans
If you want a validation to run only when two conditions are true, what should you do?
AUse :if and :unless together
BUse two separate validations
CCombine conditions in one method or lambda for :if
DUse :only_if option
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.