Model Associations in Ruby
From the Ruby on Rails cheat sheet · Models & Active Record · verified Jul 2026
Model Associations
Define relationships between models
ruby
class User < ApplicationRecord
has_many :posts
has_one :profile
end
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
end✅ belongs_to creates foreign key relationship
💡 dependent: :destroy deletes associated records
🔍 has_many :through for many-to-many relationships
⚡ Use counter_cache to avoid COUNT queries
modelsassociationsrelationships