Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a custom validation method in a Rails model.
Ruby on Rails
class User < ApplicationRecord validate :[1] def custom_age_check errors.add(:age, "must be at least 18") if age < 18 end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name in the validate call than the method defined.
Forgetting to define the custom validation method.
✗ Incorrect
The method name used in the validate call must match the custom validation method defined in the model.
2fill in blank
mediumComplete the code to add an error message inside the custom validation method.
Ruby on Rails
def check_username if username.blank? errors.[1](:username, "can't be blank") end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add_error' or other incorrect method names.
Forgetting to specify the attribute when adding errors.
✗ Incorrect
The correct method to add an error message in Rails validations is 'errors.add'.
3fill in blank
hardFix the error in the custom validation method to correctly check if email contains '@'.
Ruby on Rails
def email_format unless email.[1]('@') errors.add(:email, "must contain @") end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like 'contains' or 'has'.
Forgetting the question mark at the end of 'include?'.
✗ Incorrect
The correct Ruby method to check if a string contains a substring is 'include?'.
4fill in blank
hardFill both blanks to create a custom validation that checks if password length is at least 6.
Ruby on Rails
def password_length_check if password.[1] < [2] errors.add(:password, "is too short") end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' instead of 'length' (both work but only one is correct here).
Using the wrong number for minimum length.
✗ Incorrect
Use 'length' to get the password length and compare it to 6 for minimum length validation.
5fill in blank
hardFill all three blanks to create a custom validation that adds an error if age is not between 18 and 65.
Ruby on Rails
def age_range_check unless age [1] 18 [2] age [3] 65 errors.add(:age, "must be between 18 and 65") end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' instead of '&&' which allows invalid ages.
Reversing the comparison operators.
✗ Incorrect
Check that age is greater or equal to 18 and less or equal to 65 using '>=' and '<=' with '&&' between conditions.