添加具有祖先的集合组

时间:2014-07-26 22:58:10

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

我使用ancestry gem与位置模型。如果用户选择父项如何显示子项,则单击子项显示兄弟姐妹?

如何在用户_form.html.erb中应用?

enter image description here

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

1 个答案:

答案 0 :(得分:0)

<强>祖先

该过程相对简单,考虑到ancestry为您提供了一系列方法来实现这一目标:

enter image description here

您要做的是在javascript中创建一个on change函数,将相关对象传递给您的控制器,它将返回您需要的结果:

#config/routes.rb
resources :locations do
   get :siblings
end

#app/controllers/locations_controller.rb
Class LocationsController < ApplicationController
   repsond_to :json, only: :siblings

   def siblings
      @location = Location.find params[:id]
      respond_with @location.children #-> might need some logic to differentiate between siblings / children
   end
end

这将允许您定义ajax方法来管理来自数据的响应:

#app/assets/javascripts/application.js
$(document).on("change", "#your_select", function(){
   var id = $(this).val();

   $.ajax({
      url: "/locations/" + id + "/siblings",
      dataTye: "json",
      success: function(data) {
          // append result to your other select boxes
      }      
   });
});

这应该为您提供所需的功能