首页 > 解决方案 > 更新 json 列中的单个属性会触发完整的列更新

问题描述

我想知道这是错误还是正常的rails行为。我在 5.2.3

我的 PostgreSQL 数据库上有一个 JSON 类型的列,看起来像这样

id | name | address(json)
1  | josh | { line1: nil, line2: nil, city: nil }

如果我做:

@account = Account.find(1)
@account.address['city'] = "new york"
@account.save

这通过重写整个 json 和每个属性来更新整个列。我想这可能会在某些用例中引入竞争条件,而不仅仅是更新地址。

 UPDATE "accounts" SET "address" = $1, "updated_at" = $2 WHERE "accounts"."id" = $3  [["address", "{'is_foreign':false,'line1':'54 Lemon Ave",'line2':null,'city':'new york','state':'NY','country':'US'}"], ["updated_at", "2019-11-15 18:09:07.698093"], ["id", 2]]

标签: ruby-on-railspostgresql

解决方案


它看起来像一个正常的行为,试试这个,它应该可以工作

@account = Account.find(1)
address_json = @account.address
address_json['city'] = 'new york'
@account.address = address_json
@account.save

希望有帮助!

此处提供更多有用信息 -如何在 Postgres 9.4 中对 JSONB 类型的列执行更新操作


推荐阅读