buren / association_count

Small gem to include association counts where they are needed.
MIT License
3 stars 2 forks source link

split select into two terms #5

Closed lostapathy closed 5 years ago

lostapathy commented 5 years ago

At present, if a model has two can_count associations setup, a query for both at the same time will select table.* twice.

class Product < ActiveRecord::Base
  has_many :reviews
  has_many :photos
  can_count :reviews
  can_count :photos
end

Product.include_review_count.include_photos_count

Will yield a query like:

SELECT 
  products.*, 
  COUNT(reviews.id) as review_count_raw, 
  products.*,
  COUNT(photos.id) as photo_count_raw 
FROM ...

With this patch, it will generate a query like:

SELECT 
  products.*, 
  COUNT(reviews.id) as review_count_raw, 
  COUNT(photos.id) as photo_count_raw 
FROM ...

By separating the select(#{table_name}.*") from the select("count"), ActiveRecord is able to de-duplicate the select clauses at query generation time, which saves the database from querying out and transferring the same data twice. I suspect this would have a large memory impact in rails for large data sets, but have not tested that.

buren commented 5 years ago

Nice! Thank you @lostapathy 👍