Ruby
Consolidate database count queries.
Posted
August 25, 2009 08:03
by
delano, tagged with
rails
@areas = Area.all
<ul>
<% @areas.each do |area| %>
<li><span class="titoloAree"><%=h area.name%></span> (<%=h area.videos.count%>)</li>
<%end%>
</ul>
## Controller
@areas = Area.all
## View [html_rails]
<ul>
<% @areas.each do |area| %>
<li><span class="titoloAree"><%=h area.name%></span> (<%=h area.videos.count%>)</li>
<%end%>
</ul>
Refactorings
No refactoring yet !
August 25, 2009,
August 25, 2009 14:22,
permalink
No rating.
Login to rate!
@areas = Area.all(:include => :videos)
September 3, 2009,
September 03, 2009 06:24,
permalink
No rating.
Login to rate!
In my rails application an Area has_many Videos.
I wrote a (part of a) view that lists all the areas, and for each area shows the count
of the videos that belong to it.
My code works, but makes a different database query for each Area, which I suppose
is not terribly efficient -- do you know of any way to improve it? Thanks!