I had a very similar problem except I wanted to eager load the category's path
instead of just the root
. Unfortunately, eager loading only works for associations. The Ancestry navigators (parent
, root
, path
, ancestors
, etc.) are all methods, not associations, so you can't eager load them.
My solution was to eager load the entry's category association and then use model-level caching (see Railscast #115) on Category
to cache the path
(you could amend to root
in your case):
category.rb
def cached_path
Rails.cache.fetch([self, "path"]) { path.to_a }
end
entries_controller.rb
def index
@entries = Entry.includes(:category)
end
views/entries/index.html.haml
- @entries.each do |entry|
= entry.category.cached_path.map{ |c| c.name }.join(" / ")
Hope that helps.