【问题标题】:Rails 4 - destroy action deletes wrong recordRails 4 - 销毁操作删除错误的记录
【发布时间】:2015-11-12 18:13:59
【问题描述】:

我正在向 Rails 发出 ajax 请求,将数据传递给 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)

有人知道为什么吗?

【问题讨论】:

  • 请发布您的活动模型。
  • 里面什么都没有。只是类声明,无论如何更新我的帖子
  • find_by 更改为find

标签: ruby-on-rails ruby ajax ruby-on-rails-3


【解决方案1】:

为什么你使用find_by它在你想使用不同的属性来搜索时使用:

Event.find(params[:id])

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

Event.find_by_id(params[:id])

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

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

如果没有找到具有此 ID 的记录,则使用 find_by! 引发异常:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 2014-01-22
      • 1970-01-01
      • 2011-07-01
      • 2023-03-17
      • 1970-01-01
      • 2017-04-18
      • 2020-02-08
      • 1970-01-01
      相关资源
      最近更新 更多