Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres JSON field update with ActiveRecord

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
like image 355
typeoneerror Avatar asked Mar 27 '15 17:03

typeoneerror


1 Answers

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
like image 105
Arup Rakshit Avatar answered Sep 20 '22 03:09

Arup Rakshit