Yuval Hager - Drupal development and consulting

  • About
  • Services
  • Contact
Home

rails

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 lab
  • Add new comment
  • Read more
Tags:
  • acts_as_tree
  • rails
Syndicate content
I love Smashing Magazine!
Fervens Drupal theme by Leow Kah Thong. Designed by Design Disease and brought to you by Smashing Magazine.