def self.all_leaves
leaves = []
Category.roots.each do |category|
leaves << category.children
end
leaves.flatten
end
Refactorings
No refactoring yet !
bob
July 23, 2009, July 23, 2009 23:56, permalink
def self.all_leaves
Category.roots.collect { |category| category.children }.flatten
end
# or
def self.all_leaves
Category.roots.inject([]) { |acc, category| acc + category.children }
end
Kett
July 24, 2009, July 24, 2009 00:00, permalink
This should work...
def self.all_leaves
Category.roots.inject([]) { |result,category| result.concat(category.children) }
end
steved
July 24, 2009, July 24, 2009 19:00, permalink
# if you have Symbol#to_proc def self.all_leaves Category.roots.map(&:children).flatten end
Tj Holowaychuk
July 24, 2009, July 24, 2009 21:00, permalink
If you have the 'every' gem:
def self.all_leaves Category.roots.every.children.flatten end
Ben Marini
September 21, 2009, September 21, 2009 02:16, permalink
I'm assuming this is ActiveRecord, and each call to children is another query. If that's the case, you could probably do something like this to be more efficiant.
def self.all_leaves Category.find :all, :conditions => "parent_id IS NOT NULL" end
i dont find a better way to do this, and i dont like the first attribution line, anybody haz a better idea? tnx