Associations
has_many and belongs_to.
What Are Associations?
Associations declare relationships between models so Active Record can navigate related rows for you. Instead of writing join SQL, you call methods like user.posts.
- They mirror the foreign keys in your database.
- They generate helper methods automatically.
- They make code read like the domain.
belongs_to
belongs_to says this model holds a foreign key pointing to another. A Comment that belongs to a Post has a post_id column.
class Comment < ApplicationRecord
belongs_to :post
end
# comment.post returns the parent Post
# Requires a post_id column on comments