Rails 4: How to update a collection_select based on another collection_select through AJAX?

后端 未结 2 1586
Happy的楠姐
Happy的楠姐 2021-01-01 02:24

The problem: I need to filter a collection of Units based upon the selection of a collection of Organizations.

Upo

2条回答
  •  遥遥无期
    2021-01-01 02:45

    I made it, the solution was pretty simple, but the lack of updated material regarding this simple issue made it a chore bigger than it should have:

    config/routes.rb

     get 'filter_units_by_organization' => 'projects#filter_units_by_organization'
    

    controllers/projects_controller.rb

    def filter_units_by_organization
      @filtered_units = Unit.where(organization_id: params[:selected_organization])
    end
    

    views/projects/filter_units_by_organization.js.erb

    $('select#project_unit_id').html('<%= j options_from_collection_for_select(@filtered_units, :id, :name) %>');
    

    assets/javascripts/application.js

    $(function() {
        $("select#project_organization_id").on("change", function() {
            $.ajax({
                url:  "/filter_units_by_organization",
                type: "GET",
                data: { selected_organization: $("select#project_organization_id").val() }
            });
        });
    });
    

    views/projects/_form.html.erb

    <%= f.label :name %>
    <%= f.text_field :name %>
    <%= f.label :description %>
    <%= f.text_area :description %>
    <%= f.label :organization_id %>
    <%= f.collection_select :organization_id, Organization.all, :id, :name, { prompt: 'Please select' } %>
    <%= f.label :unit_id %>
    <%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %>
    <%= f.submit %>

提交回复
热议问题