4

Using awesome_nested_set with Rails 3, I've created a hierarchical categories system. To display the category selector in the view, I've 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'm attempting to order the categories in alphabetical order, on a level by level basis. If I change the nested_set_options(Category, @category) to nested_set_options(Category.order("name"), @category) this will reorder the whole categories list by name; what I want to do is reorder the children of each node alphabetically by name.

For example, I want to resulting select menu to be ordered like this:

Animal
- Bird
-- Chicken
-- Hawk
- Fish
-- Cod
-- Goldfish
-- Trout
- Mammal
-- Cat
-- Primate
--- Chimpanzee
--- Human
-- Zebra
Plant
- Tree
Chris Alley
  • 2,945
  • 2
  • 20
  • 30

2 Answers2

2

Although I am unfamiliar with awesome_nested_set, you can call order twice in Rails 3.

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

This should order Category by each level and then by name within each level. Also, you can throw this on the default scope within the model.

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

Orders are great for default scope because they don't effect any default values.

awilkening
  • 1,063
  • 8
  • 26
  • Since this post, we have realized the difficulty in using order in the default scope when dealing with data manipulation. – awilkening Oct 31 '11 at 19:13
1

You can use @item.children.except(:order).order("your_sort_column") as suggested in this stackoverflow post: awesome nested set order by

Community
  • 1
  • 1
Morgan Christiansson
  • 28,822
  • 1
  • 17
  • 13