Boss Nass
Boss Nass

Reputation: 3522

reducing db queries

i am attempting to reduce the load our database, and have read that using the :include method can help with this. i current have the following line of code that is allowing me to select all the information i need, but when i attempt to render this in my view with the count i am hitting the database over and over again

@sports = Sport.includes([:teams]).all

in my view im doing

- @sports.each do |sport|
  %tr
    %td= sport.name
    %td= sport.teams.count

and i suspect the sport.teams.count is what is causing the database to be queried over and over again. how do i fix this?

Upvotes: 0

Views: 69

Answers (2)

jvnill
jvnill

Reputation: 29599

As mischa said, you can use a counter_cache to solve your issue. But you can also look at this sql statement to get the counts

@sports = Sport.select('sports.*, (SELECT COUNT(*) FROM teams WHERE teams.sport_id = sports.id) AS teams_count')

then you can just use sport.teams_count

- @sports.each do |sport|
  %tr
    %td= sport.name
    %td= sport.teams_count

Upvotes: 1

Mischa
Mischa

Reputation: 43298

You should use a counter_cache for this. Also see this screencast.

Upvotes: 2

Related Questions