动态选择带有祖先

我的应用程序使用祖先gem。

class Location  true has_many :posts end class User < ActiveRecord::Base belongs_to :location end 

我创建了一些随机位置,

  • 阿拉斯加州
  • 加州
    • 洛杉矶
    • 弗雷斯诺
      • Cincotta(弗雷斯诺)
      • 哈蒙德(弗雷斯诺)
      • 梅尔文(弗雷斯诺)

我的问题是,如果用户选择加州,用户注册表格,显示孩子洛杉矶和弗雷斯诺,选择弗雷斯诺后,然后显示它的孩子。

我获得了下拉列表的http://www.avascript2net.com/javascript_tutorial/dropdown-list-demo.php的 javascript教程

如何使用祖先gem ?

嵌套

首先,如果您想将它们全部保存在一个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 

我无法理解您的问题,但请尝试按照本教程进行操作:

http://railscasts.com/episodes/262-trees-with-ancestry

当需要使用祖先gem时,我曾经看过它。

希望它可以帮到你。