0
0
Ruby on Railsframework~5 mins

Custom validation methods in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Avalidates_with
Bvalidates
Cvalidate
Dvalidate_with
Where do you add error messages inside a custom validation method?
Aadd_error(:attribute, "message")
Berrors.add(:attribute, "message")
Cerror.add(:attribute, "message")
Dadd.errors(:attribute, "message")
What happens if a custom validation adds an error to the model?
AThe model deletes itself
BThe model saves anyway
CThe error is ignored
DThe model will not save
Which of these is a reason to use a custom validation?
ATo check a rule built-in validators can't handle
BTo speed up saving records
CTo automatically fix errors
DTo skip validations
How do you call a custom validation method named check_name?
Avalidate :check_name
Bvalidates :check_name
Cvalidate_with :check_name
Dvalidates_with :check_name
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.