evilmartians/activerecord-slotted_counters

N+1 query when using with_slotted_counters()

Linuus opened this issue · 0 comments

What did you do?

I ran the example from the readme:

User.all.with_slotted_counters(:comments).find_each do
  _1.comments_count
end

What did you expect to happen?

I expected the counts to be preloaded.

What actually happened?

It makes a SQL query per row to fetch the count.

Additional context

I think the issue is that when you define the has_many association: https://github.com/evilmartians/activerecord-slotted_counters/blob/master/lib/activerecord_slotted_counters/has_slotted_counter.rb#L41
you have a scope. That scope messes with the preload and it has to make a call per row.

Environment

Ruby Version:

3.1.2

Framework Version (Rails, whatever):

Rails 7.0.4.2

Activerecord Slotted Counters Version:

0.1.1