CoffeeScript不适用于Rails4应用程序中的下拉菜单



我正在构建一个与Rails 4健身相关的应用程序来学习该框架。我的重点是改善用户体验,但在尝试将一些CoffeeScript代码集成到我的应用程序中时遇到了一个问题。有问题的模型被称为StrengthExercise,它有一个带有两个下拉菜单的表单。这两个菜单都填充了其他两个模型/数据库表中的内容:肌肉组和力量训练列表。力量训练模型包含以下声明:

belongs_to :muscle_group
belongs_to :strength_training_list

以下是新力量训练表格中的相关代码:

<div class="field">
  <%= f.label :muscle_group %><br />
  <%= f.collection_select :muscle_group_id, MuscleGroup.order(:name), :id, :name, include_blank: true %>
</div>
<div class="field">
  <%= f.label :strength_exercise %><br />
  <%= f.grouped_collection_select :strength_training_list_id, MuscleGroup.order(:name), :strength_training_lists, :name, :id, :name, include_blank: true %>
</div>

这两个下拉菜单包含我的数据库表中所需的数据。这不是问题所在。这就是我的困境:当用户从第一个下拉菜单中选择一个肌肉组时,我希望该"事件"触发第二个下拉菜单的相关力量练习。完成此任务的数据在相应的表中可用,但不起作用。

我研究了如何实现我想要的目标,并找到了一些有用的教程,包括Ryan Bates关于动态下拉菜单的修订版第88集。为了实现我的目标,我选择了CoffeeScript,因为它已经内置在Rails4中了。我遵循了Bates的教程,但由于某种原因,我的CoffeeScript不起作用。这是strength_exercises.js.coffee的脚本代码,它位于我的apps/javascript/目录中:

jQuery ->
  strength_training_lists = $('#strength_exercise_strength_training_list_id').html()
  console.log(strength_training_lists)
  $('#strength_exercise_muscle_group_id').change ->
  muscle_group = $('#strength_exercise_muscle_group_id :selected').text()
  options = $(strength_training_lists).filter("optgroup[label='#{Muscle group}']").html()
  console.log(options)
  if options
    $('#strength_exercise_strength_training_list_id').html(options)
  else
    $('#strength_exercise_strength_training_list_id').empty()

脚本似乎没有在更改事件上启动。在浏览器中,当我在第一个下拉菜单中选择一个肌肉组时,第二个下拉菜单不会发生任何事情。第二个下拉菜单应该填充相关的力量练习,但它保持不变。数据可用于进行此操作,因此我怀疑我在实现中做错了什么。在浏览器中加载页面不会产生任何错误。我尝试使用Firebug来排除脚本故障。然而,我是编程新手,不知道如何使用该工具来解决问题。该脚本包含控制台日志操作,但我无法看到或理解出了什么问题。我正在接近实现我所寻求的用户体验,但确实需要一些帮助来排除CoffeeScript的故障。如果您能帮助我实现下拉菜单所需的功能,我将不胜感激。非常感谢。

更改此项:

("optgroup[label='#{Muscle group}']")

到此:

("optgroup[label='#{muscle_group}']")

最新更新