0
0
Ruby on Railsframework~30 mins

has_one relationship in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding has_one Relationship in Rails
📖 Scenario: You are building a simple Rails app to manage users and their profiles. Each user has exactly one profile with personal details.
🎯 Goal: Create a User model and a Profile model with a has_one relationship from User to Profile. Set up the database tables and associations correctly.
📋 What You'll Learn
Create a User model with a has_one :profile association
Create a Profile model with a belongs_to :user association
Add a foreign key user_id to the profiles table
Use Rails conventions for migrations and model files
💡 Why This Matters
🌍 Real World
Many apps have users with one profile containing personal info. This pattern keeps data organized and easy to access.
💼 Career
Understanding has_one relationships is essential for Rails developers to model real-world data correctly and build maintainable apps.
Progress0 / 4 steps
1
Create the User model
Generate a Rails model called User with a string attribute name. Write the model file app/models/user.rb with the class User inheriting from ApplicationRecord.
Ruby on Rails
Need a hint?

The User model file should define a class User that inherits from ApplicationRecord.

2
Create the Profile model with user_id foreign key
Generate a Rails model called Profile with string attributes bio and location. Add a foreign key user_id to the profiles table. Write the model file app/models/profile.rb with the class Profile inheriting from ApplicationRecord.
Ruby on Rails
Need a hint?

The Profile model file should define a class Profile that inherits from ApplicationRecord. The migration should add user_id as a foreign key.

3
Add associations between User and Profile models
In the User model, add has_one :profile. In the Profile model, add belongs_to :user.
Ruby on Rails
Need a hint?

Use has_one :profile in User and belongs_to :user in Profile.

4
Add migration to create profiles table with user_id
Write a migration to create the profiles table with string columns bio and location, and a user_id column as a foreign key referencing users. Use t.references :user, foreign_key: true in the migration.
Ruby on Rails
Need a hint?

Use create_table :profiles and add t.references :user, foreign_key: true to link profiles to users.