底部附有答案代码
对于第二个选择框,仅显示与所选团队相关联的员工
的选择选项。
表单:
示例案例:用户选择另一个团队。员工选择选项会更新以仅显示与所选团队相关联的那些员工。
我知道解决方案是使用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
...
<%= 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
});
});
routes.rb
文件传递,然后发送到#app/controllers/task_notes_controller.rb
进行处理。那里获取并存储所有的staff_member
记录。视图中的选择框将使用#app/assets/javascripts/task_notes.js
中指定的代码进行更新。 - Neil