使用ActiveRecord更新Postgres JSON字段

typ*_*ror 6 postgresql activerecord json ruby-on-rails

什么是update与json字段一起使用的最佳方式.我希望我的JSON字段接受新密钥或更新现有密钥,但不会覆盖整个字段.ActiveRecord可以很好地更新已更改的字段,但我不明白如何将其应用于json记录中的子字段...

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
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 6

您的代码应如下所示:

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
Run Code Online (Sandbox Code Playgroud)