Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active January 29, 2020 22:28
Show Gist options
  • Select an option

  • Save StevenJL/71b6df39f65fdc75d459ae1f8b49326b to your computer and use it in GitHub Desktop.

Select an option

Save StevenJL/71b6df39f65fdc75d459ae1f8b49326b to your computer and use it in GitHub Desktop.
# Assuming User has the following association
class User
has_many :posts
end
# Running this activerecord code
users = User.all
users.each do |user|
user.posts
end
# Will generate n+1 queries, where n is the number of users, namely
# SELECT * FROM users;
# SELECT * FROM posts WHERE posts.user_id = 1;
# SELECT * FROM posts WHERE posts.user_id = 2;
# SELECT * FROM posts WHERE posts.user_id = 2;
# .....
# SELECT * FROM posts WHERE posts.user_id = n;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment