Rails 4 - destroy 操作删除了错误的记录

Rails 4 - destroy action deletes wrong record

我正在做一个 ajax 请求 rails 传递数据一个 id。

这里是 ajax

function delete_availability(id) {
    var id = id;

    $.ajax({
      type: "DELETE",
      url: "/events/" + id,
      statusCode: {

        200: function() {
          //alert("200");
        },
        202: function() {
          //alert("202");
        }
      },
      success: function(data) {

        console.log('availability deleted');

      },
      error: function(xhr) {
        alert("The error code is: " + xhr.statusText);
      }
    });
  }

我的销毁动作

def destroy

    @event = Event.find_by(params[:id]);

    respond_to do |format|
      if @event.destroy
        format.json {
          render json: {}
        }
      end
    end
  end

我的事件模型里面什么都没有

class Event < ActiveRecord::Base

end

问题是即使 rails 收到正确的 id,当它去销毁时,它会更改 id 并销毁下一个。

这里是 rails 日志:

Processing by EventsController#destroy as */*
  Parameters: {"id"=>"66"}
  Event Load (0.1ms)  SELECT  "events".* FROM "events" WHERE (66) LIMIT 1
   (0.0ms)  begin transaction
  SQL (0.2ms)  DELETE FROM "events" WHERE "events"."id" = ?  [["id", 65]]
   (2.4ms)  commit transaction
Completed 200 OK in 6ms (Views: 0.1ms | ActiveRecord: 2.8ms)

有人知道为什么吗?

您应该使用 Event.find(params[:id])Event.find_by(id: params[:id])

您的代码发生的情况是 SQL 查询找到每个事件 - WHERE (66) 对任何记录都是正确的 - find_by 从集合中获取第一条记录,并且它被摧毁。请求中的 ID 无关紧要。

为什么要使用 find_by 当您想使用不同的属性进行搜索时使用它:

Event.find(params[:id])

或者如果您不想在找不到记录时抛出异常,请使用 find_by_id

Event.find_by_id(params[:id])

或者如果您仍然想使用 find_by 如果没有找到记录,您可以使用 which returns nil:

Event.find_by(id: params[:id])

并使用 find_by! 抛出异常,如果没有找到具有此 ID 的记录:

 Event.find_by!(id: params[:id])