Yuval Hager - Drupal development and consulting

  • About
  • Services
  • Contact
Home

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:
  • acts_as_tree
  • rails

No responses to "Using option groups with acts_as_tree"

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

I love Smashing Magazine!
Fervens Drupal theme by Leow Kah Thong. Designed by Design Disease and brought to you by Smashing Magazine.