Reply to comment
Using option groups with acts_as_tree
Submitted by yhager on Fri, 12/18/2009 - 17:14
When you have a model that acts_as_tree, you might want to use that to generate a nice select element with option groups.
In your view, simply use:
<%= f.select (:category_id, option_groups_from_collection_for_select(
Category.top,
:children, :name,
:id, :name
)) %>
and add a method to your model:
def self.top
find(:all, :conditions => [ 'parent_id IS NULL' ])
end
This generates HTML like this:
<select id="product_category_id" name="product[category_id]">
<optgroup label="Europe">
<option selected="selected" value="8">France</option>
<option value="9">Spain</option>
</optgroup>
<optgroup label="America">
<option value="11">USA</option>
<option value="12">Canada</option>
</optgroup>
</select>
And it looks like this:
Tags:
