我的Rails 7应用程序使用以下模型:
Batch模型,has_many任务Task模型,belongs_to批处理资源嵌套如下:
resources :batches do
resources :tasks
end任务模型有一个completed属性,它是一个boolean。
我遵循的是本教程 --在从零开始启动新的Rails 7应用程序时,它就像一种魅力一样--在没有嵌套资源的情况下启动一个新的Rails 7应用程序--在任务索引视图中选中相应的复选框时,将任务标记为已完成的任务(反之,在任务索引视图中未选中相应的复选框时,将任务标记为未完成)。
正如上面所暗示的,本教程中的设置与我的设置之间的主要区别在于我使用嵌套资源。
因此,我对本教程中的代码作了如下调整:
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" %>当我重新启动服务器并尝试通过选中复选框将任务标记为已完成时,我会在终端中看到以下错误:
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">我碰壁了,因为我不知道下一步该怎么做:任何指导都是非常感谢的。
发布于 2022-07-13 00:14:20
在const batch_id = e.target.dataset.batch_id中用const batch_id = e.target.dataset.batchId代替tasks_controller.js解决了这一问题。
https://stackoverflow.com/questions/72958837
复制相似问题