My Rails 7 app uses the following models:
Batch
model,has_many
tasksTask
model,belongs_to
a batch
Resources are nested as follows:
resources :batches do
resources :tasks
end
The task model has a completed
attribute which is a boolean
.
I am following this tutorial — which works like a charm when starting a new Rails 7 app from scratch without nested resources — to mark tasks as completed when the corresponding checkbox is checked in the Tasks index view (and, conversely, to mark tasks as not completed when the corresponding checkbox is unchecked in the Tasks index view).
As hinted above, the main difference between the setup in the tutorial and my setup is that I use nested resources.
So, I have adapted the code from the tutorial as follows:
routes.rb
(I modified thepost "tasks/:id/toggle", to: "tasks#toggle"
route):
post "batches/:batch_id/tasks/:id/toggle", to: "tasks#toggle"
tasks_controller.js
(I added theconst batch_id ...
line):
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
(I added thebatch_id: @batch.id
line):
<%= 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" %>
When I restart the server and try to mark a task as completed by checking a checkbox, I see the following error in Terminal:
ActiveRecord::RecordNotFound (Couldn't find Batch with 'id'=undefined):
app/controllers/tasks_controller.rb:40:in `set_batch'
I also see the following error in the browser console (which does suggest that the batch_id
is not sent properly, given that is shows up as undefined
):
POST http://localhost:3000/batches/undefined/tasks/34/toggle 404 (Not Found)
Yet, when I inspect the checkbox element, it does seem that the bach_id
showing up in the 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">
I am hitting a wall, as I am not sure where to turn next to make this work: any guidance is highly appreciated.