📖 Scenario: You are building a simple Rails application to manage user profiles. Each user must have a username that is unique and does not contain any spaces. You will create a custom validation method to check that the username has no spaces.
🎯 Goal: Build a Rails model with a custom validation method that ensures the username attribute contains no spaces.
📋 What You'll Learn
Create a User model with a username attribute
Add a custom validation method called username_cannot_contain_spaces
Use validate :username_cannot_contain_spaces to call the custom validation
Add an error message to username if it contains spaces
💡 Why This Matters
🌍 Real World
Custom validations help enforce business rules that built-in validations cannot cover, such as complex formats or cross-field checks.
💼 Career
Rails developers often write custom validations to ensure data integrity and provide clear feedback to users in web applications.
Progress0 / 4 steps
1
Create the User model with username attribute
Create a Rails model class called User that inherits from ApplicationRecord. Add an attribute accessor for username.
Ruby on Rails
Hint
Use attr_accessor :username inside the User class.
2
Add custom validation method declaration
Inside the User model, add a line to call the custom validation method named username_cannot_contain_spaces using validate :username_cannot_contain_spaces.
Ruby on Rails
Hint
Use validate :username_cannot_contain_spaces to register the custom validation.
3
Define the custom validation method
Define a method called username_cannot_contain_spaces inside the User model. Inside this method, check if username includes a space character. If it does, add an error to username with the message "cannot contain spaces" using errors.add(:username, "cannot contain spaces").
Ruby on Rails
Hint
Use safe navigation &. to avoid errors if username is nil.
4
Complete the User model with custom validation
Ensure the User model includes attr_accessor :username, the line validate :username_cannot_contain_spaces, and the full method username_cannot_contain_spaces as defined previously.
Ruby on Rails
Hint
Review the full model to confirm all parts are included.
Practice
(1/5)
1. What is the main purpose of a custom validation method in a Rails model?
easy
A. To add your own rules for checking data before saving
B. To automatically generate database tables
C. To create user interface elements
D. To speed up database queries
Solution
Step 1: Understand validation role in Rails
Validations check data correctness before saving to the database.
Step 2: Identify custom validation purpose
Custom validations let you write your own rules beyond built-in checks.
Final Answer:
To add your own rules for checking data before saving -> Option A
Quick Check:
Custom validation = custom data rules [OK]
Hint: Custom validations add your own data rules [OK]
Common Mistakes:
Confusing validations with database setup
Thinking validations create UI elements
Assuming validations improve query speed
2. Which is the correct way to add a custom validation method named check_age in a Rails model?
easy
A. validates :check_age
B. validate :check_age
C. validate_check_age
D. validates_with :check_age
Solution
Step 1: Recall syntax for custom validations
Use validate :method_name to call a custom method.
Step 2: Match method name with syntax
For method check_age, syntax is validate :check_age.
Hint: Use 'validate :method_name' for custom validations [OK]
Common Mistakes:
Using 'validates' instead of 'validate' for custom methods
Adding underscores in method call
Using 'validates_with' incorrectly
3. Given this model code:
class User < ApplicationRecord
validate :check_name
def check_name
errors.add(:name, "can't be blank") if name.blank?
end
end
What happens if you try to save a User with name = ''?
medium
A. The save fails with an error on the name attribute
B. The save succeeds without errors
C. A syntax error occurs
D. The save fails but no error message is added
Solution
Step 1: Understand the custom validation logic
The method adds an error if name.blank? is true (empty string).
Step 2: Effect on saving a User with empty name
Since name is blank, error is added and save fails.
Final Answer:
The save fails with an error on the name attribute -> Option A
Quick Check:
Blank name triggers error = save fails [OK]
Hint: Blank fields trigger errors in custom validations [OK]
Common Mistakes:
Assuming save succeeds despite errors
Confusing blank? with nil check
Expecting syntax errors from valid code
4. Identify the error in this custom validation method:
class Product < ApplicationRecord
validate :check_price
def check_price
errors.add(:price, "must be positive") if price <= 0
end
end
medium
A. The method name should start with 'validate_'
B. The validation should use 'validates' instead of 'validate'
C. No error; the code is correct
D. The comparison operator should be '==' instead of '<='
Solution
Step 1: Check method naming and usage
Custom validation methods do not need 'validate_' prefix; 'validate :method' is correct.
Step 2: Verify validation logic and syntax
Using 'validate' with method and condition 'price <= 0' is valid Ruby and Rails syntax.
Final Answer:
No error; the code is correct -> Option C
Quick Check:
Custom validation syntax and logic are correct [OK]
Hint: Custom validation methods do not need special prefixes [OK]
Common Mistakes:
Adding 'validate_' prefix to method name
Using 'validates' for custom methods
Changing correct comparison operators
5. You want to create a custom validation that ensures a User's username is at least 5 characters and contains no spaces. Which code correctly implements this?
hard
A.
validate :username_rules
def username_rules
errors.add(:username, "invalid") if username.length <= 5 && username.include?(" ")
end
validate :username_rules
def username_rules
if username.length < 5 || username.include?(" ")
errors.add(:username, "must be 5+ chars and no spaces")
end
end
Solution
Step 1: Understand the validation requirements
Username must be at least 5 characters and contain no spaces.
Step 2: Analyze each option's logic
validate :username_rules
def username_rules
if username.length < 5 || username.include?(" ")
errors.add(:username, "must be 5+ chars and no spaces")
end
end
uses OR logic to add error if username is shorter than 5 or contains spaces, which matches requirements.
validate :username_rules
def username_rules
errors.add(:username, "invalid") if username.length <= 5 && username.include?(" ")
end
uses wrong comparison (<= 5 excludes 5).
Final Answer:
validate :username_rules
def username_rules
if username.length < 5 || username.include?(" ")
errors.add(:username, "must be 5+ chars and no spaces")
end
end -> Option D
Quick Check:
Custom validation logic matches requirements [OK]
Hint: Check logic carefully: use OR for combined invalid conditions [OK]
Common Mistakes:
Using AND instead of OR for combined conditions
Confusing built-in validations with custom methods