更新了底部的答案代码
对于第二个选择框,仅显示与所选团队
相关联的那些员工
的选择选项。
表格:
示例:用户选择另一个团队。工作人员选择选项更新以仅显示与所选团队关联的那些工作人员。
我知道解决方案是使用 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
});
});
最佳答案
首先,您向您的 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
有了这个,在你的 ajax
调用的 success
回调中,你会得到一个包含列表的 JSON
对象。因此,您需要清除 staff
选择并创建选项并附加到它。
// Ajax call
success: function(data) {
$("#staff_member_id").children().remove();
// Create options and append to the list
}
// Rest of Ajax call
如您所见,我没有将创建选项的代码放入列表中,但简单的搜索将有大量关于此的结果。这个想法很简单。
关于javascript - 根据 Rails 中的第一个选择列表值更改第二个选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612461/