Performance: Why associations connect models
Associations affect how Rails loads related data, impacting page load speed and memory usage.
posts = Post.includes(:user).all posts.each do |post| puts post.user.name end
posts = Post.all posts.each do |post| puts post.user.name end
| Pattern | Database Queries | Memory Usage | Load Time Impact | Verdict |
|---|---|---|---|---|
| Lazy loading associations | N+1 queries | Higher due to repeated queries | Slower with more records | [X] Bad |
| Eager loading associations | 2 queries | Lower by batching data | Faster and consistent | [OK] Good |
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