根据rails中的第一个选择列表值更改第二个选择列表

更新了底部的答案代码

对于第二个选择框,仅显示与所选team关联的staff members选择选项。

形成:

在此处输入图像描述


示例案例 :用户选择另一个团队。 工作人员选择选项更新以仅显示与所选团队相关联的工作人员。

在此处输入图像描述

我知道解决方案是使用javascript,但我在rails环境中应用它时遇到了麻烦。 我知道这个问题,但仍然无法将其应用到我的rails应用程序。


 #app/controllers/task_notes_controller.rb ... def new @task_note = TaskNote.new @teams = Team.all.includes(:staff_members) end ... 

 #app/views/task_notes/_form.html.erb ...  

# Currently displays all staff members on every team, no matter what team is selected.
...

 #app/assets/javascripts/task_notes.js $(document).ready(function(){ $("#team").on('change', function(){ alert("The new team id is: " + $(this).val() ); # The value (the id of the team) does update on selection option change. # Now I need to specify that I want the select options for the staff members # select box to update and show only staff members with this team_id }); }); 

首先,向controller发出ajax调用。 (请记住,来自ajax调用的url必须存在于您的路由中)。

 $(document).ready(function() { $("#team").on('change', function(){ $ajax({ url: "populate_other_list", type: "GET", data: {team_id: $(this).val()}, // Callbacks that will be explained }) }); 

接下来,您将在controller内进行action

 def populate_other_list team_id = params[:team_id] @staff = Staff.find_by team_id: team_id respond_to do |format| format.json { render json: @staff } end end 

有了这个,在你success回调你的ajax调用时,你会得到一个包含你的列表的JSON对象。 因此,您需要清除staff选择并创建选项并附加到其中。

 // Ajax call success: function(data) { $("#staff_member_id").children().remove(); // Create options and append to the list } // Rest of Ajax call 

正如您所看到的,我没有放置创建选项的代码并将它们放在列表中,但是简单的搜索会有很多结果。 这个想法很简单。