In my Rails app I have the following associations:

```
class Person < ApplicationRecord

  has_many :payments

  def sales_volume(range)
    payments.in_range(range).sum(&:amount)
  end

  ...

end

```

---

```
class Payment < ApplicationRecord

  belongs_to :person

  def self.in_range(range)
    select { |x| range.cover?(x.date) }
  end

  ...

end

```

In my controller I am doing...

```
@people = Person.all.sort_by { |p| p.sales_volume(@range) }

```

...and it works.

Unfortunately, though, it generates a lot of **N+1 queries**.

Is there a way to show the sales volume per `person` without generating a separate SQL query for each person?

---

*Addition:*

I've already tried eager-loading...

```
@people = Person.all.includes(:payments).sort_by { |p| p.sales_volume(@range) }

```

...but that didn't work either. Still the same number of queries.