Skip to content

Commit

Permalink
Merge pull request #5469 from mamhoff/add-order-promotions-dependent-…
Browse files Browse the repository at this point in the history
…destroy

Add foreign key constraint between order_promotions and promotions
  • Loading branch information
tvdeyen authored Nov 3, 2023
2 parents 00031a2 + f2649f7 commit a8c1d8a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion core/app/models/spree/promotion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions core/spec/models/spree/promotion_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit a8c1d8a

Please sign in to comment.