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

时间:2015-07-24 13:58:03

标签: javascript jquery ruby-on-rails ruby

更新了底部的答案代码

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

形式:

enter image description here

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

enter image description here

我知道解决方案是使用javascript,但我在rails环境中应用它时遇到了麻烦。我知道this question但我仍然无法将其应用到我的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
...
<%= select_tag('team', options_from_collection_for_select(@teams, :id, :name ) ) %>

<div class="field">
  <%= f.label :staff_member_id %><br>
  # Currently displays all staff members on every team, no matter what team is selected.
  <%= f.collection_select :staff_member_id, StaffMember.all, :id, :first_name %>
</div>
...


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

});

1 个答案:

答案 0 :(得分:8)

首先,您向ajax发出controller来电。 (请注意,url来自ajax来电的$(document).ready(function() { $("#team").on('change', function(){ $ajax({ url: "populate_other_list", type: "GET", data: {team_id: $(this).val()}, // Callbacks that will be explained }) }); 必须存在于您的路线中。

action

接下来,在controller内建立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 选择并创建选项并附加到其中。

JMX

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

相关问题