diff --git a/app/models/spree/variant.rb b/app/models/spree/variant.rb index 2937687af7..d4f3c3aade 100644 --- a/app/models/spree/variant.rb +++ b/app/models/spree/variant.rb @@ -59,6 +59,8 @@ module Spree %w(weight volume).include?(variant.product.andand.variant_unit) } + validates :unit_value, numericality: { greater_than: 0 } + validates :unit_description, presence: true, if: ->(variant) { variant.product.andand.variant_unit.present? && variant.unit_value.nil? } diff --git a/db/migrate/20210414171109_add_unit_value_constraint.rb b/db/migrate/20210414171109_add_unit_value_constraint.rb new file mode 100644 index 0000000000..ac34a8d15a --- /dev/null +++ b/db/migrate/20210414171109_add_unit_value_constraint.rb @@ -0,0 +1,10 @@ +class AddUnitValueConstraint < ActiveRecord::Migration[5.0] + def up + execute "UPDATE spree_variants SET unit_value = 1 WHERE unit_value <= 0" + execute "ALTER TABLE spree_variants ADD CONSTRAINT positive_unit_value CHECK (unit_value > 0)" + end + + def down + execute "ALTER TABLE spree_variants DROP CONSTRAINT positive_unit_value" + end +end diff --git a/db/schema.rb b/db/schema.rb index 310cc0420f..db58a7a083 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20210326094519) do +ActiveRecord::Schema.define(version: 20210414171109) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" diff --git a/spec/controllers/api/v0/variants_controller_spec.rb b/spec/controllers/api/v0/variants_controller_spec.rb index a7b3d70b81..439a03e22d 100644 --- a/spec/controllers/api/v0/variants_controller_spec.rb +++ b/spec/controllers/api/v0/variants_controller_spec.rb @@ -130,7 +130,7 @@ describe Api::V0::VariantsController, type: :controller do it "can create a new variant" do original_number_of_variants = variant.product.variants.count - api_post :create, variant: { sku: "12345", unit_value: "weight", unit_description: "L" }, product_id: variant.product.to_param + api_post :create, variant: { sku: "12345", unit_value: "1", unit_description: "L" }, product_id: variant.product.to_param expect(attributes.all?{ |attr| json_response.include? attr.to_s }).to eq(true) expect(response.status).to eq(201) diff --git a/spec/models/spree/variant_spec.rb b/spec/models/spree/variant_spec.rb index 239962a655..3589df55aa 100644 --- a/spec/models/spree/variant_spec.rb +++ b/spec/models/spree/variant_spec.rb @@ -18,6 +18,11 @@ module Spree variant.price = 0 expect(variant).to be_valid end + + it "should validate unit_value is greater than 0" do + variant.unit_value = 0 + expect(variant).to be_invalid + end end context "price parsing" do