0
0
Ruby on Railsframework~30 mins

Why associations connect models in Ruby on Rails - See It in Action

Choose your learning style9 modes available
Why associations connect models
📖 Scenario: You are building a simple blog application where authors write posts. You want to connect the Author and Post models so that each post belongs to an author, and each author can have many posts.
🎯 Goal: Create two Rails models, Author and Post, and connect them using associations so that you can easily find all posts by an author and the author of a post.
📋 What You'll Learn
Create an Author model with a name attribute
Create a Post model with a title attribute and a reference to Author
Add a has_many :posts association in the Author model
Add a belongs_to :author association in the Post model
💡 Why This Matters
🌍 Real World
Connecting models with associations is common in web apps to represent relationships like users and their posts, products and their categories, or orders and their customers.
💼 Career
Understanding Rails associations is essential for backend developers working with databases and building maintainable, efficient web applications.
Progress0 / 4 steps
1
Create the Author model with a name attribute
Create a Rails model called Author with a string attribute name.
Ruby on Rails
Need a hint?

Use rails generate model Author name:string to create the model with the name attribute.

2
Create the Post model with title and author reference
Create a Rails model called Post with a string attribute title and a reference to Author using author:references.
Ruby on Rails
Need a hint?

Use rails generate model Post title:string author:references to create the model with the title and author reference.

3
Add has_many association in Author model
In the Author model, add the association has_many :posts to connect authors to their posts.
Ruby on Rails
Need a hint?

Use has_many :posts inside the Author class to connect it to posts.

4
Add belongs_to association in Post model
In the Post model, add the association belongs_to :author to connect each post to its author.
Ruby on Rails
Need a hint?

Use belongs_to :author inside the Post class to connect it to an author.