What's the best way to use update
with a json field. I'd like my JSON field to accept new keys or update existing keys, but not overwrite the entire field. ActiveRecord does a nice job of just updating fields that changed, but I don't understand how to apply that to the sub-fields in the json record...
it 'can update settings with a plain object' do
integration = Integration.create(
name: 'Name',
json_settings: {
key1: 1,
key2: 2
}
)
integration.update(
settings: { key2: 2 }
)
// json_settings is now { "key2": 3 } but I want
// { "key1": 1, "key2": 3 }
expect(integration.json_settings['key1']).to eq('1') // fails
end
Your code should look like:
it 'can update settings with a plain object' do
integration = Integration.create(
name: 'Name',
json_settings: {
key1: 1,
key2: 2
}
)
integration.json_settings = integration.json_settings.merge { key2: 3 }
integration.save
expect(integration.json_settings['key1']).to eq(1)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With