我做到了,解决方案非常简单,但是由于缺少有关此简单问题的更新资料,因此使它比原本应做的事情繁琐得多:
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 > <%= f.label :name %><br> <%= f.text_field :name %> </div> <div > <%= f.label :description %><br> <%= f.text_area :description %> </div> <div > <%= f.label :organization_id %><br> <%= f.collection_select :organization_id, Organization.all, :id, :name, { prompt: 'Please select' } %> </div> <div > <%= f.label :unit_id %><br> <%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %> </div> <div > <%= f.submit %> </div>


