Optimize impressionist_count query via arel count with distinct option

This commit is contained in:
Ross Kaffenberger 2012-03-19 18:24:40 -04:00
parent 594889a3db
commit fcfacdfdc9
2 changed files with 2 additions and 5 deletions

View File

@ -26,10 +26,7 @@ module Impressionist
def impressionist_count(options={})
options.reverse_merge!(:filter=>:request_hash, :start_date=>nil, :end_date=>Time.now)
imps = options[:start_date].blank? ? impressions : impressions.where("created_at>=? and created_at<=?",options[:start_date],options[:end_date])
if options[:filter]!=:all
imps = imps.select(options[:filter]).group(options[:filter])
end
imps.all.size
options[:filter] == :all ? imps.count : imps.count(options[:filter], :distinct => true)
end
def update_counter_cache

View File

@ -21,7 +21,7 @@ describe Impression do
describe "#update_counter_cache" do
it "should update the counter cache column to reflect the correct number of impressions" do
lambda {
Impression.create(:impressionable_type => @widget.class.name, :impressionable_id => @widget.id)
@widget.impressions.create(:request_hash => 'abcd1234')
@widget.reload
}.should change(@widget, :impressions_count).from(0).to(1)
end