0

We build some object in our controller:

  @sites = Site.find(:all, :conditions => conditions, :order => 'group_id ASC')

And then in the view (currently), we are doing something like:

@sites.each do |site|
   %p Site Name
     = site.name
   - actual = site.estimates.where('date<?', Date.today).sum(:actual_cost)
   %p
     = actual
end

Basically like that.

And of course this fires off a query for the Sites and then a query for N sites returned. I know about eager-loading associations with @sites = Site.find(:all, :include => :estimates) but in this case it didn't matter because we're doing the SUM on the query which is special it seems.

How would I eager load the SUMs in such that I don't get all the crazy queries? Currently it's over 600...

notaceo
  • 1,093
  • 10
  • 28

1 Answers1

0

provide your conditions & ordering in this query only, which will push the result into a Hash.

    sites = Site.includes(:estimates).where('estimates.date < ? ', Date.today)
.order('sites.id ASC')

actual = 0 
sites.map { |site|
  site.estimates.map { |estimate|  actual = actual + estimate.actual_cost }
} 

From your explanation, I am assuming actual_cost is a column in estimate table.

Ajay
  • 4,199
  • 4
  • 27
  • 47