【问题标题】:How to delete another record in same table using after_destroy callback如何使用 after_destroy 回调删除同一张表中的另一条记录
【发布时间】:2016-06-13 10:58:38
【问题描述】:

我在下面的列中有一个表格

id、user_id、friend_user_id

如果 A 是 B 的朋友,那么我想插入两条记录,例如 1. user_id:1,friend_user_id:2 2. user_id:2,friend_user_id:1

我已经使用下面的 after_create 回调完成了这项工作

after_create do
        Friend.create(user_id: friend_user_id,friend_user_id: user_id)
    end

如果其中任何一条记录已被删除,我想删除两条记录。

我已经尝试了 after_destroy 回调,如下所示。

after_destroy do
        Friend.where(friend_user_id: user_id,user_id: friend_user_id).first.destroy
    end

但我收到以下错误。

2.3.0 :002 > Friend.first.destroy
  Friend Load (0.4ms)  SELECT  "friends".* FROM "friends"  ORDER BY "friends"."id" ASC LIMIT 1
   (0.2ms)  begin transaction
  SQL (0.7ms)  DELETE FROM "friends" WHERE "friends"."id" = ?  [["id", 10]]
  Friend Load (0.3ms)  SELECT  "friends".* FROM "friends" WHERE "friends"."friend_user_id" = ? AND "friends"."user_id" = ?  ORDER BY "friends"."id" ASC LIMIT 1  [["friend_user_id", 1], ["user_id", 2]]
  SQL (0.1ms)  DELETE FROM "friends" WHERE "friends"."id" = ?  [["id", 11]]
  Friend Load (0.1ms)  SELECT  "friends".* FROM "friends" WHERE "friends"."friend_user_id" = ? AND "friends"."user_id" = ?  ORDER BY "friends"."id" ASC LIMIT 1  [["friend_user_id", 2], ["user_id", 1]]
   (0.3ms)  rollback transaction
NoMethodError: undefined method `destroy' for nil:NilClass
        from /home/ubuntu/workspace/app/models/friend.rb:39:in `block in <class:Friend>'

我是 RoR 的新手。任何帮助将不胜感激。

【问题讨论】:

  • 您的 call_back 在您删除记录后执行,因此在您的删除和回调方法之间,您的值为 nil。这就是为什么,它给你这个错误

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

您的代码在这里完全错误,您最终会得到 SystemStackError,并且在 after_create 和 after_destroy 的两个地方都会发生这种情况。正在发生的事情是,当您销毁一个元素时,您的 after_destroy 回调将被执行,这将再次销毁一个元素,并且由于它已删除一个元素,它将再次执行回调,但是由于您已删除该元素,这就是您得到的原因此错误NoMethodError: undefined methoddestroy' for nil:NilClass` 因为该元素已被删除,为了获得更清晰的图片,请使用相同的代码并执行 Friend.create,您会看到我在说什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2018-08-01
    相关资源
    最近更新 更多