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