[英]Postgres JSON field update with ActiveRecord
What's the best way to use update
with a json field. 使用json字段
update
的最佳方法是什么。 I'd like my JSON field to accept new keys or update existing keys, but not overwrite the entire field. 我希望我的JSON字段接受新密钥或更新现有密钥,但不会覆盖整个字段。 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...
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.