Answer the question
In order to leave comments, you need to log in
How to make eager loading when grouping?
Hello.
There are Purchase, Shop and Category models.
The goal is to get all the stores where purchases were made with the total amount of purchases. Purchase.group(:shop).sum(:amount)
returns a Hash with the correct values (shop object and amount)
But, at the same time, when I want to get the category of the store, then for each call to shop.category there is a request to the database.
I tried to do like this:
Purchace.group(:shop).includes(shop: [:category]).sum(:amount)
class Shop < ActiveRecord::Base
belongs_to :category
belongs_to :city
has_many :purchases
end
class Category < ActiveRecord::Base
has_many :shops
end
class Purchase < ActiveRecord::Base
belongs_to :user
belongs_to :shop
end
Answer the question
In order to leave comments, you need to log in
Try preload, it looks like includes misunderstands what you want
Read more here
I'm starting to think that this is impossible... Since in calculate.rb, in the execute_grouped_calculation method, there is such a block:
if association
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
key_records = association.klass.base_class.find(key_ids)
key_records = Hash[key_records.map { |r| [r.id, r] }]
end
purchases = user.purchases.select('shop_id, sum(count)').group(:shop_id)
shop_ids = purchases.collect do |purchase| purchase.shop_id end
shops = Shop.includes(:category).find(shop_ids)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question