Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Created May 8, 2014 11:56
Show Gist options
  • Save ifyouseewendy/2bb5d89bb6b68046d905 to your computer and use it in GitHub Desktop.
Save ifyouseewendy/2bb5d89bb6b68046d905 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'mongoid'
require 'mongoid/support/query_counter'
Mongoid.configure.connect_to("mongoid_test")
def count_queries(&block)
query_counter = Mongoid::QueryCounter.new
query_counter.instrument(&block)
query_counter.events.size
end
class Post
include Mongoid::Document
has_many :comments
end
class Comment
include Mongoid::Document
belongs_to :post
field :date
end
Post.delete_all
Comment.delete_all
post1 = Post.create!
post2 = Post.create!
post3 = Post.create!
post1.comments << Comment.create!(:date => 'today')
post1.comments << Comment.create!(:date => 'today')
post2.comments << Comment.create!(:date => 'today')
post2.comments << Comment.create!(:date => 'today')
post2.comments << Comment.create!(:date => 'today')
query_counter1 = count_queries do
Post.each do |post|
post.comments.map(&:date)
end
end
puts "without incldues: #{query_counter1}"
# => 4
query_counter2 = count_queries do
Post.includes(:comments).each do |post|
post.comments.map(&:date)
end
end
puts "with includes: #{query_counter2}"
# => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment