Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add foreign key constraint between order_promotions and promotions #5469

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading