From 3ec6386e1cb43210adfcf24d5e2b358efebb0ba4 Mon Sep 17 00:00:00 2001 From: David Cook Date: Wed, 20 Sep 2023 14:31:45 +1000 Subject: [PATCH] Validate length of some product fields We know if the values are too long, so let's provide a useful message rather than generating an unhandled database error. This code seems rather repetetive, it would be good to use a shared module. I wonder if there's a gem for that. Note that the existing /products/*/edit screen doesn't even handle validation errors yet, but that's something for another day.. --- app/models/spree/product.rb | 3 ++- spec/models/spree/product_spec.rb | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/app/models/spree/product.rb b/app/models/spree/product.rb index be905c8ccc..88a6ef60c1 100755 --- a/app/models/spree/product.rb +++ b/app/models/spree/product.rb @@ -54,7 +54,8 @@ module Spree has_many :variant_images, -> { order(:position) }, source: :images, through: :variants - validates :name, presence: true + validates :name, presence: true, length: { maximum: columns_hash['name'].limit } + validates :sku, length: { maximum: columns_hash['sku'].limit } validates :variant_unit, presence: true validates :unit_value, numericality: { diff --git a/spec/models/spree/product_spec.rb b/spec/models/spree/product_spec.rb index 06ba1e2626..34d16b641f 100644 --- a/spec/models/spree/product_spec.rb +++ b/spec/models/spree/product_spec.rb @@ -163,6 +163,10 @@ module Spree expect(build(:product)).to be_valid end + it { is_expected.to validate_presence_of :name } + it { is_expected.to validate_length_of(:name).is_at_most(255) } + it { is_expected.to validate_length_of(:sku).is_at_most(255) } + it "requires a primary taxon" do expect(build(:simple_product, primary_taxon: nil)).not_to be_valid end