问题描述
我的应用程序使用祖先宝石。
My application using ancestry gem.
class Location < ActiveRecord::Base
has_ancestry :cache_depth => true
has_many :posts
end
class User < ActiveRecord::Base
belongs_to :location
end
我创建了一些随机位置,
I created some random Location,
- 阿拉斯加
- 加利福尼亚州
- 洛杉矶
- 弗雷斯诺
- 辛科塔(弗雷斯诺)
- 哈蒙德(弗雷斯诺)
- 梅尔文(弗雷斯诺)
- Alaska
- California
- Los Angeles
- Fresno
- Cincotta (Fresno)
- Hammond (Fresno)
- Melvin (Fresno)
我的问题,如果用户选择了加利福尼亚,则显示 Los Angles和 Fresno子项,然后选择 Fresno,然后显示其子项。
My question if user sign up form if User select California, display child Los Angles and Fresno, after select Fresno then display it's child.
我有下拉列表
如何与?
推荐答案
嵌套
首先,如果您想将它们全部保存在一个
下拉列表
中,我们创建了以下帮助您的帮助器:Firstly, if you wanted to keep them all in a single
dropdown
, we created the following helper which achieves it for you:#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 ) %>
这将使您能够调用单下拉菜单,已根据您的祖先协会进行嵌套
This will give you the ability to call a single dropdown, which has been nested according to your ancestry associations
-
Ajax
如果要使用双下拉框,则可能必须实现
ajax
函数以提取每个所需的数据初始下拉列表更改的时间:If you want to have double dropdown boxes, you'll probably have to implement an
ajax
function to pull the required data each time the initial dropdown changes:#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
这篇关于祖先动态选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!