Skip to content

Instantly share code, notes, and snippets.

@Bahanix
Last active March 22, 2017 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bahanix/21709355f209cdbd4086f3fe490ddb55 to your computer and use it in GitHub Desktop.
Save Bahanix/21709355f209cdbd4086f3fe490ddb55 to your computer and use it in GitHub Desktop.
N+1 queries example
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
end
# It will hit 11 times your database, that's bad!
User.limit(10).each do |user|
user.posts.each do |post|
puts post.title
end
end
# It will hit 2 times your database, that's nice!
User.limit(10).preload(:posts).each do |user|
user.posts.each do |post|
puts post.title
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment