From e1c13bc194934c15f30d276d20022b76c2f53901 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Wed, 20 Jan 2021 13:39:01 +0000 Subject: [PATCH] Fix issue with orphaned adjustments in migration --- .../20201219120055_add_order_to_adjustments.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/db/migrate/20201219120055_add_order_to_adjustments.rb b/db/migrate/20201219120055_add_order_to_adjustments.rb index 9748a4372d..d9ece7ee22 100644 --- a/db/migrate/20201219120055_add_order_to_adjustments.rb +++ b/db/migrate/20201219120055_add_order_to_adjustments.rb @@ -21,7 +21,17 @@ class AddOrderToAdjustments < ActiveRecord::Migration # Migrate adjustments on line_items Spree::Adjustment.where(order_id: nil, adjustable_type: "Spree::LineItem").includes(:adjustable).find_each do |adjustment| - adjustment.update_column(:order_id, adjustment.adjustable.order_id) + line_item = adjustment.adjustable + + # In some cases a line item has been deleted but an orphaned adjustment remains in the + # database. There is no way for this orphan to ever be returned or accessed via any scopes, + # and no way to know what order it related to. In this case we can remove the record. + if line_item.nil? + adjustment.delete + next + end + + adjustment.update_column(:order_id, line_item.order_id) end end end