嵌套
首先,如果您想将它们全部保存在一个 中dropdown
,我们创建了以下帮助程序来为您实现它:
#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
这将允许您调用:
<%= f.select(:category_ids, nested_dropdown(Category.all.arrange), prompt: "Category", selected: @category ) %>
这将使您能够调用单个下拉列表,该下拉列表已根据您的祖先关联嵌套
--
阿贾克斯
如果您想要双下拉框,您可能必须实现一个ajax
函数来在每次初始下拉列表更改时提取所需的数据:
#config/routes.rb
resources :categories do
get :select_item
end
#app/assets/javascripts/application.js
$("#first_dropdown").on("change", function(){
$.ajax({
url: "categories/"+ $(this).val() + "/select_item",
dataType: "json",
success: function(data) {
//populate second dropdown
}
})
});
#app/controllers/categories_controller.rb
Class CategoriesController < ApplicationController
respond_to :json, only: :select_item
def select_item
category = @category.find params[:category_id]
respond_with category.children
end
end