New interface to upsert custom fields

This commit is contained in:
Robin Ward 2018-03-02 12:45:34 -05:00
parent 0ec1dc9237
commit 730201d423
2 changed files with 40 additions and 0 deletions

View File

@ -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

View File

@ -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