I was using Rails 7.0.4 to make a to-do list application, but I'm trying to update my model of a checkbox using stimulus.js. For that:
index.html.erb
<tbody>
<% @tasks.each do |task| %>
<tr data-controller="task"
data-task-update-url="<%= task_path(task) %>">
<td><%= task.task_title%></td>
<td><%= task.task_date%></td>
<td>
<input type = "checkbox"
data-action = "task#toggle"
data-target = "task.completed"
<% if task.completed %> checked <% end %>>
</td>
<td>
<%= link_to edit_task_path(task) do %>
<i class="fa fa-edit"></i>
<% end %>
</td>
<td>
<%= link_to task_path(task), data: { "turbo_method": :delete, turbo_confirm: "Are you sure?" } do %>
<i class="fa fa-trash"></i>
<% end %>
</td>
</tr>
<% end %>
</tbody>
task_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "completed" ]
toggle (event) {
let formData = new FormData()
formData.append("task[completed]", this.completedTarget.checked);
fetch (this.data.get("update-url"), {
body: formData,
method: 'PATCH',
credentials: "include",
dataType: "script",
headers: {
"X-CSRF-Token": getMetaValue("csrf-token")
},
}).then(function(response) {
if (response.status != 204) {
event.target.checked = !event.target.checked
}
})
}
}
I am getting the following error:
What am I doing wrong?
Your Task
model has a task_complete
method, but you are asking for complete
in your code.
Look at the error message. It says Undefined method 'complete'
that's because nowhere in your code you have def
ined it.
You could ask another method complete?
def complete?
task_complete
end
and add that into your erb code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.