【问题标题】:Rails, how to spot what delete record with multiple associations?Rails,如何发现具有多个关联的删除记录?
【发布时间】:2021-06-29 08:52:40
【问题描述】:

我有多个关联的模型:

   class ContactsPlacesLink < ActiveRecord::Base
     belongs_to :contact, polymorphic: true, optional: true
     belongs_to :place, polymorphic: true, optional: true
   end

   class Contact < ActiveRecord::Base
     has_many :contacts_places_links, as: :contact, dependent: :delete_all
   end

   class Place < ActiveRecord::Base
     has_many :contacts_places_links, as: :place, dependent: :delete_all
   end

ContactsPlacesLink 的记录不知何故从数据库中删除了,我如何才能发现究竟是什么启动了记录的删除以及它们被删除的原因?

【问题讨论】:

  • 为什么你在你的belongs_to 关联上允许nil 值,但同时在has_many 上有dependent: :delete_all?如果ContactsPlacesLink 保留nil 值,您的预期行为是什么,或者您希望它们被删除?此外,我不清楚您的问题:哪些记录在您不注意的情况下被删除? event 是什么意思,因为您的问题中没有定义事件?
  • @spickermann 这是遗留项目,同意optional: truedependent: :delete_all 同时很奇怪)我会稍微纠正一下主要问题

标签: ruby-on-rails ruby activerecord ruby-on-rails-5


【解决方案1】:

如果您在本地调试,您可以添加一个临时的 before_destroy 回调来停止删除并查看堆栈跟踪以确定它来自何处(假设删除是通过 ActiveRecord 层发生的)。

class ContactsPlacesLink < ActiveRecord::Base
  before_destroy { raise "destroy attempted" }
end

【讨论】:

  • 我需要在生产中发现问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多