Skip to content

A platform for community discussion. Free, open, simple.

New interface to upsert custom fields

Robin Ward730201d4231f
diff --git a/app/models/concerns/has_custom_fields.rb b/app/models/concerns/has_custom_fields.rb
index 519f8deb510..b33b4fa213e 100644
--- a/app/models/concerns/has_custom_fields.rb
+++ b/app/models/concerns/has_custom_fields.rb
@@ -155,6 +155,20 @@ module HasCustomFields
!@custom_fields || @custom_fields_orig == @custom_fields
end
+ # `upsert_custom_fields` will only insert/update existing fields, and will not
+ # delete anything. It is safer under concurrency and is recommended when
+ # you just want to attach fields to things without maintaining a specific
+ # set of fields.
+ def upsert_custom_fields(fields)
+ fields.each do |k, v|
+ row_count = _custom_fields.where(name: k).update_all(value: v)
+ if row_count == 0
+ _custom_fields.create!(name: k, value: v)
+ end
+ custom_fields[k] = v
+ end
+ end
+
def save_custom_fields(force = false)
if force || !custom_fields_clean?
dup = @custom_fields.dup
diff --git a/spec/components/concern/has_custom_fields_spec.rb b/spec/components/concern/has_custom_fields_spec.rb
index f1bf5933cb5..2097583a4a3 100644
--- a/spec/components/concern/has_custom_fields_spec.rb
+++ b/spec/components/concern/has_custom_fields_spec.rb
@@ -215,5 +215,31 @@ describe HasCustomFields do
test_item.save_custom_fields(true)
expect(test_item.reload.custom_fields).to eq(expected)
end
+
+ describe "upsert_custom_fields" do
+ it 'upserts records' do
+ test_item = CustomFieldsTestItem.create
+ test_item.upsert_custom_fields('hello' => 'world', 'abc' => 'def')
+
+ # In memory
+ expect(test_item.custom_fields['hello']).to eq('world')
+ expect(test_item.custom_fields['abc']).to eq('def')
+
+ # Persisted
+ test_item.reload
+ expect(test_item.custom_fields['hello']).to eq('world')
+ expect(test_item.custom_fields['abc']).to eq('def')
+
+ # In memory
+ test_item.upsert_custom_fields('abc' => 'ghi')
+ expect(test_item.custom_fields['hello']).to eq('world')
+ expect(test_item.custom_fields['abc']).to eq('ghi')
+
+ # Persisted
+ test_item.reload
+ expect(test_item.custom_fields['hello']).to eq('world')
+ expect(test_item.custom_fields['abc']).to eq('ghi')
+ end
+ end
end
end