Search code examples
ruby-on-railseager-loadingpolymorphic-associations

Eager load polymorphic model that belongs to a certain model type


In my models I have

class Group < ApplicationRecord      
    has_many :payments, as: :paymentable   
    has_many :users
end

class User < ApplicationRecord  
  has_many   :payments, as: :paymentable   
  belongs_to :group    
end

class Payment < ApplicationRecord  
  belongs_to :paymentable, polymorphic: true
end

I would like to calculate the sum of the total user payments per group so in the controller I have this:

Group.all.each do |group|  
  group.users.each do |user|
    user.payments.each do |payment|
         ............
         ...............
    end
  end
end

How can I eliminate n+1 queries?

I tried

Group.includes(:users, :payments).each do |group| 

but this results in loading the payments that belong to Groups when I want to load the ones that belong to Users...


Solution

  • You need to use Group.includes(users: :payments).each do... to include payments for a group via its users. What happens in this case is we prefetch users of a group along with payments related to each user. That way, if you loop over users and use user.payments it won't make a call to fetch payments again.