将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
答案 0 :(得分:4)
您的代码应如下所示:
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