Search code examples
ruby-on-railsruby-on-rails-4ruby-on-rails-3.2ruby-on-rails-3.1ancestry

Add Collection group with ancestry


Iam using ancestry gem with location model. If user select parent how display children, then click children display siblings?

How can apply in user _form.html.erb?

enter image description here

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

Solution

  • Ancestry

    The process would be relatively simple, considering ancestry gives you a series of methods to achieve this:

    enter image description here

    What you'll want to do is create an on change function in javascript to pass the relative object through to your controller, which it will return the results you need:

    #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
    

    This will allow you to define ajax methods to manage the response from the data:

    #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
          }      
       });
    });
    

    This should provide you with the functionality you need