Nested select option

I’m using closure_tree for my Category model to structure the parent child relationships.

closure_tree provides a method to get the hierarchy as nested hashes:

How do I create hierarchical options for select form?

I started with this def on my Category model but it doesn’t seem to work and also I’m not sure if this is a right approach.

def self.nested_option(node_or_leaf = null, result = null)
    result ||= []
    node_or_leaf ||= Category.hash_tree
    node_or_leaf.each do |k,v|
     if (v.leaf?)
        separator = ''
        node_or_leaf.depth.times { separator = separator + '-' }
        result << [, [separator +,]]
        nested_option(v, result)

@shankard, I’m not sure I understand what the final result you want is. Is it a drop-down where each option looks like:


Yes, I want like below in my select box

--another parent
----another child1
----another child2

Ok, that makes sense. I think you may have nested you arrays too deeply. Rails select form helpers take an array of options in the following format:

  ['--parent', parent_id],
  ['----child', child_id],
  ['--other_parent', other_parent_id]

However, your method outputs the following array:

# not sure what is
  [, ['--parent', parent_id]],
  [, ['----child', child_id]],
  [, ['--other_parent', other_parent_id]]

Taking a closer look at the code, I’ve spotted a couple other issues:

  1. You only generate options for leaf nodes
  2. There are two nulls in the constructor. Ruby uses nil to represent the concept of nothing. This will probably raise an error.

thanks @joelq for correcting the errors with null. Coming from PHP bg, I didn’t realize that null caused the error.