破坏Active Record中的孤立多态关联

时间:2017-11-14 19:38:45

标签: ruby-on-rails postgresql polymorphic-associations

我最近在我的Rails应用程序中使用多态关联创建了一个通知系统。一切运行良好,直到系统停止显示某些用户的通知。我意识到罪魁祸首是一个孤儿通知 - Notification.notifiable_id正在返回一个不存在的用户。这是一个图表:

Notification is created on Comment creation

用户模型:

deliveryManagerQuoteResponse
.Quotes
.SelectMany(p=>p.QuoteDetails)
.Where(p=>p.DeliveryFee.HasValue)
.Orderby(p=>p.DeliveryFee)
.FirstOrDefault();

因此,负责创建通知的用户仍有可能删除其帐户,并将通知记录孤立在一端。

问题: 1.如何删除未找到Notification.notifiable_id的所有通知?

  1. 如何防止此问题在将来破坏通知系统?
  2. 我在发布之后意识到我误解了多态关联。我实际上已经设置了Notification.notifiable来指向用户创建的注释,而不是用户本身。

    我通过修改评论模型(以及其他作为'通知'的模型)解决了问题#2

    deliveryManagerQuoteResponse
      .Quotes
      .SelectMany(p=>p.QuoteDetails.Select(q=>new{Quote=p,Detail=q}))
      .Where(p=>p.Detail.DeliveryFee.HasValue)
      .Orderby(p=>p.Detail.DeliveryFee)
      .FirstOrDefault()?.Quote;
    

1 个答案:

答案 0 :(得分:1)

  1. 用于数据修复

    Notification.all.each do |notification|
      notification.destroy if notification.notifiable.nil?
    end
    
  2. 您的dependent: :destroy上似乎缺少冒号。这可能会在用户记录被销毁时阻止您的通知被正确销毁。