stefankroes / ancestry

Organise ActiveRecord model into a tree structure
MIT License
3.72k stars 459 forks source link

Ancestry Selectbox with optgroups for the parent nodes #165

Open mikeroher opened 10 years ago

mikeroher commented 10 years ago

Hey, I'm trying to make ancestry output HMTL like:

 <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>

where Swedish Cars would be the parent node and Volvo and Saab would be the child nodes. I've looked at the ancestry wiki but it only explains how to make a select box with dashes for the child nodes.

The way I'm currently doing it is through a helper method which takes in the roots of the node as a parameter but it seems extremely inefficient.

  def generate_category_dropdown(categories)
    @category_dropdown = ''
    @categories.each do |category|
        if category.children.any?
          @category_dropdown << "<optgroup label=\"#{category.name}\">"
          category.children.each do |child|
            @category_dropdown << "<option value=\"#{child.name}\">#{child.name}</option>"
          end
          @category_dropdown << "</optgroup>"
        else
          @category_dropdown << "<option value=\"#{category.name}\">#{category.name}</option>"
        end
    end
    @category_dropdown
  end
ghost commented 10 years ago
TreeNode.arrange_serializable
stefankroes commented 10 years ago

Mike,

I'm not sure you should be using ancestry in this scenario. It seems to me you have a tree with exactly two layers in which all nodes on the first layer are car brand categories and all nodes on the second layer are car brands. Additionally, the car brand categories aren't selectable in this example. It would we better to just create two models CarBrand and CarBrandCategory where CarBrand has_one CarBrandCategory and not user ancestry at all.

mikeroher commented 10 years ago

Stefan, thanks for the reply! I do in fact have a tree with only two layers. However, the cars is self-referential. I assumed ancestry would've made this easier. Would this be achieved through setting the foreign_key? The cars also have many parts where the parts use STI. I'm pretty sure they're unrelated but worth mentioning, nonetheless.

Thanks, Mike