Last active
January 29, 2020 22:28
-
-
Save StevenJL/71b6df39f65fdc75d459ae1f8b49326b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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