Nested Select in Rails
Posted
by James
on Stack Overflow
See other posts from Stack Overflow
or by James
Published on 2010-05-17T21:32:36Z
Indexed on
2010/05/18
23:40 UTC
Read the original article
Hit count: 264
I am working on a Rails application which uses categories
for items
.
My category
model is self-joined so that 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 which allows a user to create an item
which currently lists all categories in a select, but they are all listed together:
<%= f.label :category_id %>
<%= select :item, :category_id, Category.all.collect {|c| [ c.title, c.id ]} %>
So the select looks something like this:
Category1
Category2
Category3BelongsTo2
Category4BelongsTo1
But what I want is:
Category1
- Category4BelongsTo1
Category2
- Category3BelongsTo2
Is there a helper for this (which would be awesome!)? If not, how could I accomplish this?
Thanks!
© Stack Overflow or respective owner