Skip to content

Commit a140d56

Browse files
Fixed: don't destroy dependent associations if we cannot destroy the Product/Variant
Previously : ensure_no_line_items callback could stop deleting the Product/Variant but associations (with dependent: :destroy) were deleted whatsoever, as this is a rails bug (see rails/rails#3458)
1 parent 38ef7a7 commit a140d56

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

Diff for: core/app/models/spree/product.rb

+4-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ class Product < Spree::Base
2626

2727
acts_as_paranoid
2828

29+
# we need to have this callback before any dependent: :destroy associations
30+
# https://github.com/rails/rails/issues/3458
31+
before_destroy :ensure_no_line_items
32+
2933
has_many :product_option_types, dependent: :destroy, inverse_of: :product
3034
has_many :option_types, through: :product_option_types
3135
has_many :product_properties, dependent: :destroy, inverse_of: :product
@@ -88,7 +92,6 @@ class Product < Spree::Base
8892
after_save :run_touch_callbacks, if: :anything_changed?
8993
after_save :reset_nested_changes
9094
after_touch :touch_taxons
91-
before_destroy :ensure_no_line_items
9295

9396
before_validation :normalize_slug, on: :update
9497
before_validation :validate_master

Diff for: core/app/models/spree/variant.rb

+4-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class Variant < Spree::Base
1212
:shipping_category_id, :meta_description, :meta_keywords,
1313
:shipping_category
1414

15+
# we need to have this callback before any dependent: :destroy associations
16+
# https://github.com/rails/rails/issues/3458
17+
before_destroy :ensure_no_line_items
18+
1519
with_options inverse_of: :variant do
1620
has_many :inventory_units
1721
has_many :line_items
@@ -48,7 +52,6 @@ class Variant < Spree::Base
4852

4953
after_create :create_stock_items
5054
after_create :set_master_out_of_stock, unless: :is_master?
51-
before_destroy :ensure_no_line_items
5255

5356
after_touch :clear_in_stock_cache
5457

Diff for: core/spec/models/spree/order_merger_spec.rb

+3-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,9 @@ module Spree
124124
end
125125

126126
it "should create errors with invalid line items" do
127-
variant_2.destroy
127+
# we cannot use .destroy here as it will be halted by
128+
# :ensure_no_line_items callback
129+
variant_2.really_destroy!
128130
subject.merge!(order_2)
129131
expect(order_1.errors.full_messages).not_to be_empty
130132
end

0 commit comments

Comments
 (0)