📖 Scenario: You are building a simple Rails application to manage user profiles. Each user must have a username that is not too short or too long to keep the data consistent and user-friendly.
🎯 Goal: Create a Rails model User with a username attribute. Add a length validation to ensure the username is at least 3 characters and at most 15 characters long.
📋 What You'll Learn
Create a Rails model called User with a username attribute
Add a length validation on username to require minimum 3 characters
Add a length validation on username to require maximum 15 characters
Use Rails built-in validation syntax for length
💡 Why This Matters
🌍 Real World
Length validations are common in web apps to ensure user inputs like usernames, passwords, or descriptions meet expected size limits.
💼 Career
Understanding Rails validations is essential for backend developers working with Rails to enforce data integrity and improve user experience.
Progress0 / 4 steps
1
Create the User model with username attribute
Create a Rails model called User with a string attribute username.
Ruby on Rails
Hint
Define a class User that inherits from ApplicationRecord.
2
Add minimum length configuration
Add a validation to the User model that requires the username to have a minimum length of 3 characters using validates :username, length: { minimum: 3 }.
Ruby on Rails
Hint
Use validates :username, length: { minimum: 3 } inside the model class.
3
Add maximum length configuration
Extend the length validation on username to also require a maximum length of 15 characters using validates :username, length: { minimum: 3, maximum: 15 }.
Ruby on Rails
Hint
Add maximum: 15 inside the length hash.
4
Complete the User model with length validation
Ensure the User model has the complete length validation on username with minimum 3 and maximum 15 characters using validates :username, length: { minimum: 3, maximum: 15 }.
Ruby on Rails
Hint
Check that the validation line is exactly as required.
Practice
(1/5)
1. What does the length validation in Rails do?
easy
A. It checks how many characters a text field contains.
B. It validates the numerical value of a field.
C. It ensures a field is not empty.
D. It checks if a field contains only letters.
Solution
Step 1: Understand the purpose of length validation
Length validation controls the number of characters allowed in a text field.
Step 2: Compare options with this purpose
Only It checks how many characters a text field contains. matches this description exactly.
Final Answer:
It checks how many characters a text field contains. -> Option A
Quick Check:
Length validation = character count check [OK]
Hint: Length validation controls character count in text fields [OK]
Common Mistakes:
Confusing length with numerical value validation
Thinking it checks for empty fields
Assuming it validates character types
2. Which of the following is the correct syntax to validate that a username has a minimum length of 5 characters in Rails?