awesome_nested_set with optgroup labels
-
14-06-2021 - |
Question
I am using the awesome_nested_set gem located here https://github.com/collectiveidea/awesome_nested_set. I would like to make the parent categories optgroup labels but am at a loss on how to make that happen or if it is even possible. Is there an example somewhere of this behavior?
Solution
This is certainly not the most efficient way to do this, but it met the requirement of the task.
<select name="category_id" data-placeholder="Select a Category" class="chzn-select">
<option value=""></option>
<% @cats.each do |cat| %>
<optgroup label="<%= cat.name %>">
<% cat.children.each do |child| %>
<option value="<%= child.id %>"><%= child.name %></option>
<% end %>
</optgroup>
<% end %>
</select>
OTHER TIPS
A little late, but I had the same question and solved it by using a helper method according to https://github.com/collectiveidea/awesome_nested_set/blob/master/lib/awesome_nested_set/helper.rb
module ApplicationHelper
def grouped_nested_set_options(class_or_item, mover = nil)
if class_or_item.is_a? Array
items = class_or_item.reject { |e| !e.root? }
else
class_or_item = class_or_item.roots if class_or_item.respond_to?(:scope)
items = Array(class_or_item)
end
result = []
group = []
items.each do |root|
root.class.associate_parents(root.self_and_descendants).map do |i|
if i.level == 0
group = []
group.push yield(i)
group.push []
result.push group
else
if mover.nil? || mover.new_record? || mover.move_possible?(i)
group[1].push [yield(i), i.primary_id]
end
end
end.compact
end
result
end
end
That way you can just use grouped_nested_set_options instead of nested_set_options and you can still use rails' form helpers for generating the html.