Nested selection in Rails

I'm working on a Rails app that uses categories

for items

.

My model category

is self-connected, so categories can be nested:

class Category < ActiveRecord::Base
  has_many :items

  # Self Join (categories can have subcategories)
  has_many   :subcategories, :class_name => "Category", :foreign_key => "parent_id"
  belongs_to :parent,        :class_name => "Category"
  ...
end

      

I have a form that allows the user to create item

that currently displays all the categories in a select element, but they are all listed together:

<%= f.label :category_id %>
<%= select :item, :category_id, Category.all.collect {|c| [ c.title, c.id ]} %>

      

So, the selection looks something like this:

Category1
Category2
Category3BelongsTo2
Category4BelongsTo1

      

But I want:

Category1
  - Category4BelongsTo1
Category2
  - Category3BelongsTo2

      

Is there a helper for this (which would be awesome!)? If not, how can I do this?

Thanks!

+2


a source to share


3 answers


You might want to look at act_as_nested_set or awesome_nested_set



+3


a source


awesome_nested_set made this a piece of cake.

After installation, I added lft

both rgt

to the category table and removed the self-join. Then rebuild the category table using Category.rebuild!

. Then the selection can be easily filled in as follows:



<%= f.select :parent_id, nested_set_options(Category, @category) {|c| "#{'-' * c.level} #{c.title}" } %>

      

+1


a source


Maybe grouped_options_for_select will help you

0


a source







All Articles