Techioz Blog

Ajax で処理できないエンティティ

概要

「タスク」オブジェクトの「ステータス」パラメータを変更するには、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