What is the N+1 query problem and how do you fix it?

Answer

The N+1 query problem occurs when code iterates over N records and makes 1 additional database query per record, resulting in N+1 total queries. Example: @posts.each { |p| puts p.author.name } — 1 query for posts, then N queries for authors. Fix with eager loading: @posts = Post.includes(:author) generates 2 queries regardless of N. Use the Bullet gem to detect N+1 queries in development. Also use eager_load (single LEFT OUTER JOIN) when filtering on association columns, and preload (separate queries) otherwise.