ActiveRecord::RecordNotFound (找不到带有 'id'=undefined 的批处理) 与 Rails 7 刺激和嵌套资源



我的Rails 7应用程序使用以下模型:

  • Batch模型,has_many任务
  • Task模型,belongs_toa批

资源嵌套如下:

resources :batches do
resources :tasks
end

任务模型有一个completed属性,它是一个boolean

我遵循这个教程-当从头开始一个新的Rails 7应用程序没有嵌套的资源时,它就像一个魅力-当tasks索引视图中对应的复选框被选中时,将任务标记为已完成(相反,当tasks索引视图中对应的复选框未选中时,将任务标记为未完成)。

如上所述,本教程中的设置与我的设置之间的主要区别在于我使用了嵌套资源。

所以,我从教程中改编了代码如下:
  • routes.rb(我修改了post "tasks/:id/toggle", to: "tasks#toggle"路由):

post "batches/:batch_id/tasks/:id/toggle", to: "tasks#toggle"

  • tasks_controller.js(我添加了const batch_id ...行):
toggle(e) {
const id = e.target.dataset.id
const batch_id = e.target.dataset.batch_id
const csrfToken = document.querySelector("[name='csrf-token']").content
  • _task.html.erb(我添加了batch_id: @batch.id行):
<%= form.check_box :completed,
data: {
batch_id: @batch.id,
id: task.id,
action: "tasks#toggle"
},
class: "mr-2 align-middle bg-gray-50 border-gray-300 focus:ring-3 focus:ring-blue-300 h-5 w-5 rounded checked:bg-green-500" %>

当我重新启动服务器并尝试通过选中复选框将任务标记为完成时,我在Terminal中看到以下错误:

ActiveRecord::RecordNotFound (Couldn't find Batch with 'id'=undefined):
app/controllers/tasks_controller.rb:40:in `set_batch'

我还在浏览器控制台看到以下错误(这确实表明batch_id没有正确发送,因为它显示为undefined):

POST http://localhost:3000/batches/undefined/tasks/34/toggle 404 (Not Found)

然而,当我检查复选框元素时,似乎bach_id显示在HTML:

<input data-batch-id="6" data-id="26" data-action="tasks#toggle" class="mr-2 align-middle bg-gray-50 border-gray-300 focus:ring-3 focus:ring-blue-300 h-5 w-5 rounded checked:bg-green-500" type="checkbox" value="1" name="task[completed]" id="task_completed">

我正在碰壁,因为我不确定下一步该在哪里做这项工作:任何指导都非常感谢。

将tasks_controller.js中的const batch_id = e.target.dataset.batch_id替换为const batch_id = e.target.dataset.batchId解决了这个问题。

最新更新