@object = Object.find(:first,
:conditions => [‘object.id = ?’, params[:id]],
:include => [:user, {:comments => [{:children => :user}, :user]}])
That :include statement is troublesome. I am trying to eager-load
comments so that there will be 0 database queries during rendering. In
my experience, queries during rendering slow things down quite a bit,
especially when you’re querying for a lot of little things, like
comments or forum posts.
So far the above code was the only way I got one of my actions/views to
work without queries during rendering. The problem is that it looks
sloppy as hell, and I’m not sure if it’s optimized.
I am trying to find an Object, then eager load the User that owns that
Object; then eager load the Comments for that Object, then eager load
the Users that own those Comments; and then eager load the children of
those Comments, and then eager load the Users that own those
child-Comments. (For some reason :include => :comments only loads
parent comments when using acts_as_tree, so I have to get the children
separately.)
This is what leads me to this extra-convoluted :include. Is there a
better way to do this or is this about as good as it gets?
class User < ActiveRecord::Base
has_many :objects
has_many :comments
end
class Object < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Comment < ActiveRecord::Base
acts_as_tree
belongs_to :object
belongs_to :user
end