Rails - eager load the number of associated records, but not the record themselves.
Posted
by Max Williams
on Stack Overflow
See other posts from Stack Overflow
or by Max Williams
Published on 2010-05-12T11:42:01Z
Indexed on
2010/05/12
11:44 UTC
Read the original article
Hit count: 279
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
© Stack Overflow or respective owner