diff --git a/app/models/spree/product.rb b/app/models/spree/product.rb index 56e6150621..5c7d55e1bd 100755 --- a/app/models/spree/product.rb +++ b/app/models/spree/product.rb @@ -77,6 +77,7 @@ module Spree after_update :touch_supplier, if: :saved_change_to_primary_taxon_id? around_destroy :destruction after_save :update_units + after_touch :touch_supplier # -- Scopes scope :with_properties, ->(*property_ids) { @@ -333,7 +334,12 @@ module Spree # Assume the product supplier is the supplier of the first variant # Will breack if product has mutiple variants with different supplier - variants.first.supplier.touch + first_variant = variants.first + + # The variant is invalid if no supplier is present, but this method can be triggered when + # importing product. In this scenario the variant has not been updated with the supplier yet + # hence the check. + first_variant.supplier.touch if first_variant.supplier.present? end def touch_distributors diff --git a/spec/models/spree/product_spec.rb b/spec/models/spree/product_spec.rb index 1106ecd92c..fbe396b709 100644 --- a/spec/models/spree/product_spec.rb +++ b/spec/models/spree/product_spec.rb @@ -334,6 +334,14 @@ module Spree expect { product.touch } .to change { supplier.reload.updated_at } end + + context "when the first variant is missing supplier" do + it "doesn't blow up" do + product.variants.first.update_attribute(:supplier_id, nil) + + expect { product.touch }.to_not raise_error + end + end end it "updates units when saved change to variant unit" do