salsify/goldiloader

Preload Aggregations

Closed this issue · 1 comments

Hi there,

thanks for a really nice gem. I'm just using it for a couple of days, but I already love it!

I am currently working on a small extension to Goldiloader that would allow preloading aggregations. My goal is to achieve something like this:

class User < ActiveRecord::Base
  has_many :posts
  def post_count
    preloaded(:post_counts) do |ids|
      Post
        .where(user_id: ids)
        .group(:user_id)
        .count
    end
  end
end

As soon as the post_count method would be called, it will check if the block has already been called for the related auto_include_context. If not, it would call it once per collection. Afterwards, the preloaded value would be returned. This would obviously also work with other aggregations like maximum, sum, etc.

My question is: Would you be open to such an addition to Goldiloader? If not, I might choose building a separate gem instead.

That's a cool idea! I'd definitely be open to accepting the contribution if it didn't add too much complexity.