0
0
Ruby on Railsframework~30 mins

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

Choose your learning style9 modes available
Understanding belongs_to Relationship in Rails
📖 Scenario: You are building a simple blog application where each Comment belongs to a Post. This means every comment is linked to exactly one post.
🎯 Goal: Create a Comment model that correctly uses the belongs_to relationship to associate each comment with a post.
📋 What You'll Learn
Create a Post model with a title attribute
Create a Comment model with a content attribute
Add a belongs_to :post association in the Comment model
Add a has_many :comments association in the Post model
💡 Why This Matters
🌍 Real World
This pattern is common in blog platforms, forums, and social media apps where items like comments, reviews, or replies belong to a main post or item.
💼 Career
Understanding belongs_to and has_many associations is essential for Rails developers to model database relationships correctly and build functional web applications.
Progress0 / 4 steps
1
Create the Post model with a title
Create a Rails model called Post with a string attribute title.
Ruby on Rails
Need a hint?

Use rails generate model Post title:string to create the model with the title attribute.

2
Create the Comment model with content and post reference
Create a Rails model called Comment with a string attribute content and a reference to post (foreign key).
Ruby on Rails
Need a hint?

Use rails generate model Comment content:string post:references to create the model with the correct attributes.

3
Add belongs_to association in Comment model
In the Comment model, add the line belongs_to :post to set up the association.
Ruby on Rails
Need a hint?

Use belongs_to :post inside the Comment class.

4
Add has_many association in Post model
In the Post model, add the line has_many :comments to complete the two-way association.
Ruby on Rails
Need a hint?

Use has_many :comments inside the Post class.