动态选择带有祖先

时间:2014-07-20 23:09:19

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ancestry

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

class Location < ActiveRecord::Base
 has_ancestry :cache_depth => true
 has_many :posts
end

class User < ActiveRecord::Base
 belongs_to :location
end

我创建了一些随机位置,

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

我的问题如果用户在用户选择加利福尼亚时注册表单,则在选择弗雷斯诺后显示儿童洛杉矶和弗雷斯诺,然后显示它的孩子。

我获得了下拉列表http://www.plus2net.com/javascript_tutorial/dropdown-list-demo.php

的javascript教程

如何使用ancestry gem

2 个答案:

答案 0 :(得分:2)

<强>嵌套

首先,如果您想将它们全部保存在一个dropdown中,我们创建了以下帮助程序,它可以为您实现:

enter image description here

#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

如果您想拥有双下拉框,则每次初始下拉列表更改时,您可能必须实施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

答案 1 :(得分:0)

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

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

在需要使用祖先宝石时我曾经看过它。

希望它可以帮到你。

相关问题