Introduction
Associations link different models so they can work together easily. This helps you organize related data like friends or orders connected to users.
Associations link different models so they can work together easily. This helps you organize related data like friends or orders connected to users.
class ModelName < ApplicationRecord
has_many :other_models
belongs_to :another_model
endhas_many when one model relates to many others.belongs_to when a model belongs to one other model.class User < ApplicationRecord
has_many :posts
endclass Post < ApplicationRecord
belongs_to :user
endclass Order < ApplicationRecord
has_many :products, through: :order_items
has_many :order_items
endclass Product < ApplicationRecord
has_many :order_items
has_many :orders, through: :order_items
endThis 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.
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
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.
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.
has_many and belongs_to?has_many declares the 'one' side of a one-to-many relationship.has_many :comments correctly declares that a model has many comments.has_many :comments -> Option Dclass Author < ApplicationRecord has_many :books end class Book < ApplicationRecord belongs_to :author end
Author.first.books return?books on an author returns their books.Author.first.books fetches the first author, then returns all books linked to that author.class Comment < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :comment end
Order records with their associated Customer data efficiently. Which association setup and query is best?Order belongs_to :customer is correct.Order.includes(:customer).all loads orders and their customers efficiently to avoid extra queries.Pass the test and this pattern moves unknown