0
0
Ruby on Railsframework~5 mins

Why associations connect models in Ruby on Rails

Choose your learning style9 modes available
Introduction

Associations link different models so they can work together easily. This helps you organize related data like friends or orders connected to users.

You want to show all posts written by a user.
You need to find the author of a comment.
You want to list all products in an order.
You want to connect a profile to its user account.
Syntax
Ruby on Rails
class ModelName < ApplicationRecord
  has_many :other_models
  belongs_to :another_model
end
Use has_many when one model relates to many others.
Use belongs_to when a model belongs to one other model.
Examples
This means a user can have many posts linked to them.
Ruby on Rails
class User < ApplicationRecord
  has_many :posts
end
This means each post belongs to one user.
Ruby on Rails
class Post < ApplicationRecord
  belongs_to :user
end
An order can include many products through order items.
Ruby on Rails
class Order < ApplicationRecord
  has_many :products, through: :order_items
  has_many :order_items
end
Each product can belong to many orders through order items.
Ruby on Rails
class Product < ApplicationRecord
  has_many :order_items
  has_many :orders, through: :order_items
end
Sample Program

This example shows how a user has many posts. When we create posts linked to the user, we can easily get all posts by calling user.posts.

Ruby on Rails
class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
end

# Create a user
user = User.create(name: "Alice")

# Create posts linked to the user
post1 = Post.create(title: "Hello", user: user)
post2 = Post.create(title: "World", user: user)

# List all posts for the user
user.posts.each do |post|
  puts post.title
end
OutputSuccess
Important Notes

Associations let Rails handle database joins behind the scenes.

Always set the foreign key correctly to connect models.

Use associations to write cleaner and simpler code.

Summary

Associations connect models to show relationships.

has_many and belongs_to are the main ways to link models.

They make it easy to get related data without complex queries.