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
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 [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With