0
0
Ruby on Railsframework~30 mins

Custom validation methods in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Validation Methods in Rails
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Review the full model to confirm all parts are included.