Closed
Description
Is there are some easy approach to get all the items of a tree as a nested hash (hash_tree) but only these that have any associations and return the number associated record to the item (with descendants)?
In my opinion it's a common task. How I'm doing it right now:
class Location < ActiveRecord::Base
acts_as_tree
has_many :places
class << self
def hash_tree_with_places(options = {})
build_hash_tree(hash_tree_scope_with_places(options[:limit_depth]))
end
def hash_tree_scope_with_places(limit_depth = nil)
select('COUNT(properties.id) AS properties_count, locations.*').
joins(:descendant_hierarchies).
joins('JOIN properties ON properties.location_id = location_hierarchies.descendant_id').
from("(#{hash_tree_scope.to_sql}) locations").
group('locations.id')
end
end
end
But I don't like it because:
- Cannot add additional scope to the table scope (at least easily; current implementation, a little bit extended, uses option for this kind of problem).
- This functionality should be embedded in the library.
Lets find the better solution and include it in the library.