1

I'm working on an application that has the following associations:

class Chart < ActiveRecord::Base
  belongs_to :chart_group
  has_many :charts, :through => :chart_groups
end

class ChartGroup < ActiveRecord::Base
  has_many :charts
  belongs_to :report
end

class Chart < ActiveRecord::Base
  belongs_to :chart_group
end

One part of the application requires that we display the top 20 reports, and for each report we display the first chart (as kind of a snapshot). They way i've been doing this is, in the controller just selecting the reports;

@reports = Report.limit(20)

and then in the views just doing;

@reports.each do |report|
   <%= report.charts.first.title %>
end

Which seems fine and runs fast, but falls foul of the "N + 1 queries problem" - i would be getting one database round trip per report, so 21 hits. So I have a couple of questions

1) How can I change my original query to get the first chart? I tried using ".joins" but the problem with that is that there can be LOADS of charts associated with any one report, and there can be hundreds of reports. I can't work out how to include the "only the first chart" part into the statement.

2) Actually doing it the way I am, I have noticed that the logs are all saying "CACHE LOAD" - is rails doing some magic here for me? Am I worrying about nothing?

4

1 に答える 1