← Back to Upcase

Nested select option


(Shankar Dhanasekaran) #1

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|
      puts k.name
     if (v.leaf?)
        separator = ''
        node_or_leaf.depth.times { separator = separator + '-' }
        result << [k.name, [separator + node_or_leaf.name, node_or_leaf.id]]
      else
        nested_option(v, result)
      end
    end
    result
  end

(Joel Quenneville) #2

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

parent-child-grandchild

(Shankar Dhanasekaran) #3

Yes, I want like below in my select box

Grandparent
--parent
----child
--another parent
----another child1
----another child2

(Joel Quenneville) #4

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 k.name is
[
  [k.name, ['--parent', parent_id]],
  [k.name, ['----child', child_id]],
  [k.name, ['--other_parent', other_parent_id]]
]

(Joel Quenneville) #5

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.

(Shankar Dhanasekaran) #6

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