Open
Description
I'm trying to build a drop-down list which shows the hierarchy of my categories. So far I have this:
class Hash
def flatten_nested; flat_map{|k, v| [k, *v.flatten_nested]} end
end
<%= select_tag :category_id,
options_for_select(
Category.hash_tree.flatten_nested.map { |c| ['- ' * c.depth + c.name, c.id] },
params[:category_id]
), { include_blank: true, class: 'category-filter chosen-select', :'data-placeholder' => 'Filter by category' }
%>
It looks "good enough", at least the "- " prefix sort of shows the outline of the hierarchy.
The issue is that calling .depth
triggers an additional SQL query per item.
Is there a more efficient way in this library to order the nodes by hierarchy, and to also know what their depth is?
The only other thing I could think of was caching the depth property on the model.