Skip to content

Instantly share code, notes, and snippets.

@wuputah
Created August 22, 2008 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuputah/6804 to your computer and use it in GitHub Desktop.
Save wuputah/6804 to your computer and use it in GitHub Desktop.
# e is for efficient. There's not really a way to eager load associations yourself
# without AR thinking you're trying to assign or create something.
attr_accessor :echildren
def self.find_all_efficiently
categories = find(:all, :order => 'position ASC, name ASC').inject(Hash.new) do |h, c|
h[c.parent_id] ||= []
h[c.parent_id] << c
h
end
roots = categories[nil]
roots.each { |r| r.echildren = categories[r.id] || []; r.echildren.each { |ch| ch.echildren = categories[ch.id] || [] } }
roots
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment