小编典典

Rails 4:如何通过AJAX基于另一个collection_select更新一个collection_select?

ajax

问题: 我需要根据 组织 集合的选择来过滤 单位 集合

选择 组织后*单位 下拉菜单应刷新以仅显示属于已知 组织单位*

这些文档:

到目前为止,这是我的代码:

楷模

class Organization < ActiveRecord::Base
  has_many :units
  has_many :projects, through: :units
end
class Unit < ActiveRecord::Base
  belongs_to :organization
  has_many :projects
end
class Project < ActiveRecord::Base
  belongs_to :organizaton
  has_one :organization, through: :unit
end

查看 app / views / projects / _form.html.erb

<%= form_for(@project) do |f| %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.label :organization_id %><br>
    <%= f.collection_select :organization_id, Organization.all, :id, :name %>
  </div>
  <div class="field">
    <%= f.label :unit_id %><br>
    <%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

控制器 项目控制器

def new
  @project = Project.new
end

def project_params
  params.require(:project).permit(:name, :description, :organization_id, :unit_id)
end

我该如何工作?


阅读 211

收藏
2020-07-26

共1个答案

小编典典

我做到了,解决方案非常简单,但是由于缺少有关此简单问题的更新资料,因此使它比原本应做的事情繁琐得多:

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

视图/项目/filter_units_by_organization.js.erb

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

资产/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

<div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.label :organization_id %><br>
    <%= f.collection_select :organization_id, Organization.all, :id, :name, { prompt: 'Please select' } %>
  </div>
  <div class="field">
    <%= f.label :unit_id %><br>
    <%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
2020-07-26