我需要发出一个ajax请求来更改我的“任务”对象的“状态”参数。 脚本,没错,我可以获得任务的 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 %>
文件routes.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更改状态,但得到了一个无法处理的实体
StrongParameters
。
我会把它改为:
def update_status
@task = Task.find(params[:id])
new_status = params.require(:task).permit(:status)
@task.update(status: new_status)
end