如何在Rails 3的下拉列表中安排Ancestry树中的条目?

我有一个下拉列表,其中填充了使用祖先的表中的数据。

我想在列表中排列数据,以便将条目与其兄弟姐妹以及父母一起分组。

此代码正常,但不排列条目: true }) %>

我试过这一行: true }) %>然后我得到消息:#的未定义方法`name_nb’

我究竟做错了什么? 我该如何安排参赛作品?

在我的应用程序中,我有4个深度级别模型。 这是我用于下拉列表的代码。

控制器:

 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 

查看,haml和formtastics:

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

PS我知道这不是有效的解决方案,但它确实有效。 另外看看祖先维基

更新@mikhail的回答:

 #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 

这对我有用(Rails 4):<%= f.collection_select:parent_id,Category.order(:name),:id,:name,include_blank:true%>