3

I have a dropdown list which is populated with data from a table that is using ancestry.

I want to arrange the data in the list, so that the entries are grouped together with their siblings, and under their parents.

This code is working, but doesn't arrange the entries: <%= builder.select("id", Location.all.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %>

I have tried this line: <%= builder.select("id", Location.arrange.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %> Then I get the message: undefined method `name_nb' for #

What am I doing wrong? How can I arrange the entries?

1

3 Answers 3

12

In my application i have 4 depth level model. This is a code that im use for dropdown.

Controller:

before_filter :collection_for_parent_select, :except => [:index, :show]

  def collection_for_parent_select
    @categories = ancestry_options(Category.unscoped.arrange(:order => 'name')) {|i| "#{'-' * i.depth} #{i.name}" }
  end

  def ancestry_options(items)
    result = []
    items.map do |item, sub_items|
      result << [yield(item), item.id]
      #this is a recursive call:
      result += ancestry_options(sub_items) {|i| "#{'-' * i.depth} #{i.name}" }
    end
    result
  end

View, with haml and formtastics:

= f.input :parent_id, :as => :select, :collection => @categories

P.S. I know this is not the efficient solution, but it works. Also take a look at ancestry wiki

1
  • Thank's a lot! In the form I didn't get the :parent_id thing to work, but I used a string with the name of the field instead, and now it works very well! Oct 7, 2011 at 7:38
3

Update to @mikhail's answer:

#app/views/your_view.html.erb
<%= f.select(:category_ids, nested_dropdown(Category.all.arrange)) %>

#app/helpers/application_helper.rb
def nested_dropdown(items)
    result = []
    items.map do |item, sub_items|
        result << [('- ' * item.depth) + item.name, item.id]
        result += nested_dropdown(sub_items) unless sub_items.blank?
    end
    result
end
0

This works for me (Rails 4): <%= f.collection_select :parent_id, Category.order(:name), :id, :name, include_blank: true %>

1
  • It's missing siblings (or indents). A plain list does not look as a tree.
    – sekrett
    Nov 8, 2016 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.