From d8dcd143733beb2f27221b06b1d578f35141f3b7 Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Tue, 3 Oct 2023 17:25:46 +0200 Subject: [PATCH 1/2] Add dependent: :destroy to Spree::Order#order_promotions We found a lot of orphaned records in our database due to this missing dependent: :destroy. --- core/app/models/spree/order.rb | 2 +- core/spec/models/spree/order_spec.rb | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/core/app/models/spree/order.rb b/core/app/models/spree/order.rb index d7aa5dbab60..67021f3544e 100644 --- a/core/app/models/spree/order.rb +++ b/core/app/models/spree/order.rb @@ -104,7 +104,7 @@ def states foreign_key: :order_id, dependent: :destroy, inverse_of: :order - has_many :order_promotions, class_name: 'Spree::OrderPromotion' + has_many :order_promotions, class_name: 'Spree::OrderPromotion', dependent: :destroy has_many :promotions, through: :order_promotions # Payments diff --git a/core/spec/models/spree/order_spec.rb b/core/spec/models/spree/order_spec.rb index 8c0ca2a6cf1..eef3df40c5a 100644 --- a/core/spec/models/spree/order_spec.rb +++ b/core/spec/models/spree/order_spec.rb @@ -1818,4 +1818,18 @@ def validate(line_item) end end end + + describe "order deletion" do + let(:order) { create(:order) } + let(:promotion) { create(:promotion) } + + subject { order.destroy } + before do + order.promotions << promotion + end + + it "deletes join table entries when deleting an order" do + expect { subject }.to change { Spree::OrderPromotion.count }.from(1).to(0) + end + end end From 9e4a2c906b9c74082b28386b262406ceef4635ef Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Fri, 27 Oct 2023 10:50:10 +0200 Subject: [PATCH 2/2] Add foreign key constraint to Spree::OrderPromotions table This adds a foreign key constraint that makes sure at the database level that we don't have non-existent order IDs in the spree_orders_promotions table. --- .../20231027084517_add_order_promotions_foreign_key.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 core/db/migrate/20231027084517_add_order_promotions_foreign_key.rb diff --git a/core/db/migrate/20231027084517_add_order_promotions_foreign_key.rb b/core/db/migrate/20231027084517_add_order_promotions_foreign_key.rb new file mode 100644 index 00000000000..8660de79afc --- /dev/null +++ b/core/db/migrate/20231027084517_add_order_promotions_foreign_key.rb @@ -0,0 +1,10 @@ +class AddOrderPromotionsForeignKey < ActiveRecord::Migration[7.0] + def up + Spree::OrderPromotion.left_joins(:order).where(spree_orders: { id: nil }).delete_all + add_foreign_key :spree_orders_promotions, :spree_orders, column: :order_id, validate: false, on_delete: :cascade + end + + def down + remove_foreign_key :spree_orders_promotions, :spree_orders + end +end