Sort menu selects menu alphabetically with awesome_nested_set

Using awesome_nested_set with Rails 3, I created a hierarchical category system. To display the category selector in the view, I used the following code:

<%= form.select :parent_id, options_for_select(nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" }.unshift(["No Parent", nil]), @category.parent_id) %>

I am trying to sort the categories alphabetically, level by level. If I change the value of nested_set_options(Category, @category) to nested_set_options(Category.order("name"), @category) , this will change the order of the list of all categories by name; what i want to do is reorder the names of each of the node alphabetically by name.

For example, I want the following menu to be selected as a result:

 Animal - Bird -- Chicken -- Hawk - Fish -- Cod -- Goldfish -- Trout - Mammal -- Cat -- Primate --- Chimpanzee --- Human -- Zebra Plant - Tree 
+4
source share
2 answers

Although I am not familiar with awesome_nested_set, you can call Rails 3 twice.

 Category.order(:level).order(:name) 

This should sort the category by each level, and then by name at each level. Alternatively, you can cast this in the default area in the model.

 class Category < ActiveRecord::Base default_scope order('level, name') ... end 

Orders are great for the default area because they do not affect the default values.

+2
source

You can use @item.children.except(:order).order("your_sort_column") as suggested in this article stackoverflow: amazing nested dial order by

+1
source

Source: https://habr.com/ru/post/1332863/


All Articles