提问人:Alex Nunes 提问时间:9/3/2023 更新时间:9/3/2023 访问量:47
Ajax 中不可处理的实体
Unprocessable entity in Ajax
问:
我需要发出ajax请求来更改我的“task”对象的“status”参数。 脚本,没错,我可以获取任务的 ID 和新状态,这就是我所需要的。但是,我相信错误出在 routes.rb 文件或我放入控制器的 update_status 函数中,甚至在 ajax url 中。它给出以下错误:jquery-1.12.4.js:10254 PATCH http://127.0.0.1:3000/tasks/13/update_status 422(不可处理的实体)
index.html.erb 中的 js 和 ajax:
<script>
$(function() {
var taskId;
$(".drag").draggable({
revert: "invalid",
start: function(event, ui) {
// Stores the task ID when the drag starts
taskId = ui.helper.data("task-id");
}
});
$(".box").droppable({
accept: ".drag",
drop: function(event, ui) {
// When a child div is dropped onto a parent div
$(this).append(ui.helper); // Move a div filha para a div pai
// Get the new status based on the parent div
var newStatus = $(this).attr("id");
// Simulate an AJAX request to update task status
console.log("Tarefa " + taskId + " movida para " + newStatus);
$.ajax({
url: "/tasks/" + taskId + "/update_status",
method: "PATCH",
data: { task: { status: newStatus } },
success: function(response) {
console.log(response);
}
});
}
});
});
</script>
<%= link_to "New task", new_task_path %>
文件路由.db:
Rails.application.routes.draw do
resources :tasks do
member do
patch 'update_status' # Nome da rota personalizada
end
end
root to: "static_pages#index"
end
文件的一部分tasks_controller.rb:
def update
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to task_url(@task), notice: "Task was successfully updated." }
format.json { render :show, status: :ok, location: @task }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def update_status
@task = Task.find(params[:id])
# Verifique se o status fornecido é válido (você pode adicionar suas próprias validações aqui)
new_status = params[:status]
@task.update(status: new_status)
end
我尝试使用ajax更改状态,但得到了一个无法处理的实体
答:
1赞
spickermann
9/3/2023
#1
该代码可能会引发错误,因为它不使用 StrongParameters
。
我建议将其更改为:
def update_status
@task = Task.find(params[:id])
new_status = params.require(:task).permit(:status)
@task.update(status: new_status)
end
评论
0赞
Alex Nunes
9/4/2023
我试过了,但仍然没有用
0赞
Alex Nunes
9/4/2023
此外,我将其编程为在到达update_status功能后立即显示控制台.log(“我到达这里”),但它不会打印此消息,因此它可能甚至没有到达此功能
0赞
spickermann
9/4/2023
然后它可能是一个失败的 - 例如身份验证。该请求的日志文件条目(in )是什么样子的?响应的正文(不仅仅是状态代码)是什么样子的?你有没有尝试过改成)?before_action
log/development.log
create
create!
评论
"/tasks/" + taskId