diff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rb index 697c6ff22a8..d901fbebc0c 100644 --- a/core/app/models/spree/promotion.rb +++ b/core/app/models/spree/promotion.rb @@ -14,7 +14,7 @@ class Promotion < Spree::Base has_many :promotion_actions, autosave: true, dependent: :destroy, inverse_of: :promotion alias_method :actions, :promotion_actions - has_many :order_promotions, class_name: "Spree::OrderPromotion" + has_many :order_promotions, class_name: "Spree::OrderPromotion", inverse_of: :promotion, dependent: :destroy has_many :orders, through: :order_promotions has_many :codes, class_name: "Spree::PromotionCode", inverse_of: :promotion, dependent: :destroy diff --git a/core/db/migrate/20231031175215_add_promotion_order_promotion_foreign_key.rb b/core/db/migrate/20231031175215_add_promotion_order_promotion_foreign_key.rb new file mode 100644 index 00000000000..289e1437d2a --- /dev/null +++ b/core/db/migrate/20231031175215_add_promotion_order_promotion_foreign_key.rb @@ -0,0 +1,10 @@ +class AddPromotionOrderPromotionForeignKey < ActiveRecord::Migration[7.0] + def up + Spree::OrderPromotion.left_joins(:promotion).where(spree_promotions: { id: nil }).delete_all + add_foreign_key :spree_orders_promotions, :spree_promotions, column: :promotion_id, on_delete: :cascade + end + + def down + remove_foreign_key :spree_orders_promotions, :spree_orders + end +end diff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rb index dc7677bac57..449e06730b6 100644 --- a/core/spec/models/spree/promotion_spec.rb +++ b/core/spec/models/spree/promotion_spec.rb @@ -939,4 +939,20 @@ expect(order.adjustment_total).to eq(-10) end end + + describe "promotion deletion" do + subject { promotion.destroy! } + + let(:promotion) { create(:promotion) } + let(:order) { create(:order) } + + before do + order.promotions << promotion + end + + it "destroys associated order promotions" do + expect(Spree::OrderPromotion.count).to eq(1) + expect { subject }.to change { Spree::OrderPromotion.count }.from(1).to(0) + end + end end