我有一个下拉列表,其中填充了使用祖先的表中的数据。
我想排列列表中的数据,以便条目与其 sibling 分组在一起,并位于其 parent 之下。
此代码可以工作,但不会排列条目:
<%= 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 }) %>
然后我收到消息:
# 的未定义方法“name_nb”
我做错了什么?我该如何安排参赛作品?
最佳答案
在我的应用程序中,我有 4 个深度级别的模型。这是我用于下拉菜单的代码。
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
使用 haml 和 formattastics 查看:
= f.input :parent_id, :as => :select, :collection => @categories
附注我知道这不是有效的解决方案,但它确实有效。还要看看血统wiki
关于ruby-on-rails - 如何在 Rails 3 的下拉列表中排列祖先树中的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7674754/