From 3d4f0ebb7b6659deeb70eb88990f14f3280ce7c7 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Wed, 11 Nov 2020 20:24:21 +0000 Subject: [PATCH] Ensure variants don't end up with invalid data when a product's variant_unit is changed Fixes an issue where a product's variant_unit value is changed from "weight" to "items" and some of the product's variants can be left in an invalid state, which in turn breaks cloning of order cycles (with fatal errors). --- app/models/spree/variant.rb | 7 +++++++ spec/models/spree/variant_spec.rb | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/app/models/spree/variant.rb b/app/models/spree/variant.rb index 9b8fe730ca..d8782c9936 100644 --- a/app/models/spree/variant.rb +++ b/app/models/spree/variant.rb @@ -65,6 +65,7 @@ module Spree before_validation :set_cost_currency before_validation :update_weight_from_unit_value, if: ->(v) { v.product.present? } + before_validation :ensure_unit_value after_save :save_default_price after_save :update_units @@ -297,5 +298,11 @@ module Spree exchange_variants(:reload).destroy_all yield end + + def ensure_unit_value + return unless product&.variant_unit == "items" && unit_value.nil? + + self.unit_value = 1.0 + end end end diff --git a/spec/models/spree/variant_spec.rb b/spec/models/spree/variant_spec.rb index 333b039f39..530d8be080 100644 --- a/spec/models/spree/variant_spec.rb +++ b/spec/models/spree/variant_spec.rb @@ -783,4 +783,17 @@ module Spree expect(e.reload.variant_ids).to be_empty end end + + describe "#ensure_unit_value" do + let(:product) { create(:product, variant_unit: "weight") } + let(:variant) { create(:variant, product_id: product.id) } + + context "when a product's variant_unit value is changed from weight to items" do + it "sets the variant's unit_value to 1" do + product.update(variant_unit: "items") + + expect(variant.unit_value).to eq 1 + end + end + end end