From 7fbbefe36365bea16cfd29eddcccd0b20c81264c Mon Sep 17 00:00:00 2001 From: Daniel Waterworth Date: Wed, 29 Nov 2023 14:18:47 -0600 Subject: [PATCH] FIX: Allow setting an array custom field to a singleton value (#24636) Also, validation happens per item in an array field. --- app/models/concerns/has_custom_fields.rb | 11 ++--------- spec/lib/concern/has_custom_fields_spec.rb | 7 +++++++ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/app/models/concerns/has_custom_fields.rb b/app/models/concerns/has_custom_fields.rb index 6174bd13a9d..0429e70f206 100644 --- a/app/models/concerns/has_custom_fields.rb +++ b/app/models/concerns/has_custom_fields.rb @@ -20,14 +20,7 @@ module HasCustomFields def validate(obj, name, value) return if value.nil? - size = - if Array === type || (type != :json && Array === value) - value.map { |v| serialize(v).bytesize }.max || 0 - else - serialize(value).bytesize - end - - if size > max_length + if serialize(value).bytesize > max_length obj.errors.add( :base, I18n.t("custom_fields.validations.max_value_length", max_value_length: max_length), @@ -281,7 +274,7 @@ module HasCustomFields field_type = descriptor.type if Array === field_type || (field_type != :json && Array === value) - value = value || [] + value = Array(value || []) value.compact! sub_type = field_type[0] diff --git a/spec/lib/concern/has_custom_fields_spec.rb b/spec/lib/concern/has_custom_fields_spec.rb index 0ebba7bbda1..4987f74a284 100644 --- a/spec/lib/concern/has_custom_fields_spec.rb +++ b/spec/lib/concern/has_custom_fields_spec.rb @@ -134,6 +134,13 @@ RSpec.describe HasCustomFields do expect(db_item.custom_fields).to eq("a" => "b", "c" => "d") end + it "handles assigning singleton values to array fields" do + CustomFieldsTestItem.register_custom_field_type "array", [:integer] + test_item = CustomFieldsTestItem.new + test_item.custom_fields = { "array" => "1" } + test_item.save + end + it "handles arrays properly" do CustomFieldsTestItem.register_custom_field_type "array", [:integer] test_item = CustomFieldsTestItem.new