我有一个下拉列表,其中填充了使用祖先的表中的数据。
我想在列表中安排数据,以便将条目与其兄弟姐妹及其父母一起分组。
此代码正常运行,但不安排条目:
<%= builder.select("id", Location.all.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %>
我试过这一行:
<%= builder.select("id", Location.arrange.collect {|l| [ l.name_nb, l.id ] }, { :include_blank => true }) %>
然后我收到消息:
#
我做错了什么?我该如何安排参赛作品?
答案 0 :(得分:12)
在我的应用程序中,我有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
P.S。我知道这不是有效的解决方案,但它确实有效。另请查看祖先wiki
答案 1 :(得分:3)
更新@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
答案 2 :(得分:0)
这对我有用(Rails 4): &lt;%= f.collection_select:parent_id,Category.order(:name),:id,:name,include_blank:true%&gt;