Recall & Review
beginner
What is a custom validation method in Rails?
A custom validation method is a user-defined method inside a Rails model that checks if an object meets specific rules beyond built-in validations. It helps ensure data is correct before saving.
Click to reveal answer
beginner
How do you tell Rails to use a custom validation method?
You use the
validate :method_name syntax inside the model. Rails then calls that method during validation.Click to reveal answer
beginner
What should a custom validation method do if the data is invalid?
It should add an error message to the model's
errors collection using errors.add(:attribute, "message"). This prevents saving and shows the problem.Click to reveal answer
intermediate
Why use custom validation methods instead of built-in validators?
Custom validations let you check complex or unique rules that built-in validators can't handle, like comparing two fields or checking external conditions.Click to reveal answer
beginner
Example: How to write a custom validation method that ensures a user's age is at least 18?
Inside the User model, define a method like:<br>
def adult_age errors.add(:age, "must be at least 18") if age && age < 18 end validate :adult_age
Click to reveal answer
Which keyword tells Rails to run a custom validation method?
✗ Incorrect
Use
validate :method_name to run a custom validation method.Where do you add error messages inside a custom validation method?
✗ Incorrect
The correct syntax is
errors.add(:attribute, "message").What happens if a custom validation adds an error to the model?
✗ Incorrect
Adding errors prevents the model from saving until fixed.
Which of these is a reason to use a custom validation?
✗ Incorrect
Custom validations handle special rules not covered by built-in ones.
How do you call a custom validation method named
check_name?✗ Incorrect
Use
validate :check_name to run the method during validation.Explain how to create and use a custom validation method in a Rails model.
Think about where to put the method and how Rails knows to run it.
You got /3 concepts.
Describe why and when you would choose a custom validation method over built-in validators.
Consider what built-in validators can't do.
You got /3 concepts.