Last active
March 22, 2017 12:06
-
-
Save Bahanix/21709355f209cdbd4086f3fe490ddb55 to your computer and use it in GitHub Desktop.
N+1 queries example
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
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