【问题标题】:Postgres JSON field update with ActiveRecord使用 ActiveRecord 更新 Postgres JSON 字段
【发布时间】:2015-03-27 17:52:20
【问题描述】:

在 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

【问题讨论】:

    标签: ruby-on-rails json postgresql activerecord


    【解决方案1】:

    您的代码应如下所示:

    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 的内存版本更新整个哈希。
    • 是的,答案是正确的。我认为你在这方面想得太深了,这是不必要的。至少在这个问题中没有关于 atomicity 的内容。 OP 要求的不是删除旧的键/值,而是执行 merge 操作。
    猜你喜欢
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多