Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用ActiveRecord更新Postgres JSON字段_Ruby On Rails_Json_Postgresql_Activerecord - Fatal编程技术网

Ruby on rails 使用ActiveRecord更新Postgres JSON字段

Ruby on rails 使用ActiveRecord更新Postgres JSON字段,ruby-on-rails,json,postgresql,activerecord,Ruby On Rails,Json,Postgresql,Activerecord,在json字段中使用update的最佳方式是什么。我希望我的JSON字段接受新键或更新现有键,但不覆盖整个字段。ActiveRecord在更新更改的字段方面做得很好,但我不知道如何将其应用于json记录中的子字段 it 'can update settings with a plain object' do integration = Integration.create( name: 'Name', json_settings: { key1: 1,

在json字段中使用
update
的最佳方式是什么。我希望我的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

您的代码应该如下所示:

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

好的,这就是我要做的,但我不确定rails是否有任何方法可以在默认情况下使用合并更新该字段。是的,我很好奇是否有方法让AR也进行原子更新。如果在询问此问题时没有,请参见AR 5.2。这个答案实际上并没有回答这个问题。@jrochkind这个问题也与任何原子更新无关。“接受新键或更新现有键,但不要覆盖整个字段”--“原子更新”这个词可能不合适,但我看到它被称为“原子更新”。这个答案导致AR代码用AR的内存版本更新整个哈希。是的,答案是正确的。我认为你在这个问题上想得太深了,这是不必要的。至少在这个问题上,原子性一点也没有。OP要求的不是删除旧键/值,而是执行合并操作。