Created
May 8, 2014 11:56
-
-
Save ifyouseewendy/2bb5d89bb6b68046d905 to your computer and use it in GitHub Desktop.
mongoid by "4.0.0.beta1", https://github.com/mongoid/mongoid/blob/master/examples/mongoid_test.rb
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
#!/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