Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - eager load the number of associated records, but not the record themselves

I have a page that's taking ages to render out. Half of the time (3 seconds) is spent on a .find call which has a bunch of eager-loaded associations. All i actually need is the number of associated records in each case, to display in a table: i don't need the actual records themselves. Is there a way to just eager load the count? Here's a simplified example:

@subjects = Subject.find(:all, :include => [:questions])

In my table, for each row (ie each subject) i just show the values of the subject fields and the number of associated questions for each subject. Can i optimise the above find call to suit these requirements?

I thought about using a group field but my full call has a few different associations included, with some second-order associations, so i don't think group by will work.

@subjects = Subject.find(:all, :include => [{:questions => :tags}, {:quizzes => :tags}], :order => "subjects.name")

:tags in this case is a second-order association, via taggings. Here's my associations in case it's not clear what's going on.

Subject
  has_many :questions
  has_many :quizzes

Question
  belongs_to :subject
  has_many :taggings
  has_many :tags, :through => :taggings

Quiz
  belongs_to :subject
  has_many :taggings
  has_many :tags, :through => :taggings

Grateful for any advice - max

like image 406
Max Williams Avatar asked Sep 19 '25 07:09

Max Williams


1 Answers

I believe the best is using :counter_cache on belongs_to association.

class Subject < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :subject, :counter_cache => true
end

To use counter_cache you'll also need to add a questions_count column to your subjects table.

From railsapi.com:

:counter_cache
Caches the number of belonging objects on the associate class through the use of increment_counter and decrement_counter. The counter cache is incremented when an object of this class is created and decremented when it’s destroyed [...]

like image 75
Ju Nogueira Avatar answered Sep 21 '25 23:09

Ju Nogueira