ruby-on-rails - 更新 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]]
解决方案
它看起来像一个正常的行为,试试这个,它应该可以工作
@account = Account.find(1)
address_json = @account.address
address_json['city'] = 'new york'
@account.address = address_json
@account.save
希望有帮助!
此处提供更多有用信息 -如何在 Postgres 9.4 中对 JSONB 类型的列执行更新操作
推荐阅读
- c - 使用 C 中的多线程进行长数素数检测
- typescript - 使用打字稿验证字符串中的第一个字母大小写
- r - R:从 SpatialGridDF 转换时,raster() 会更改像素大小
- javascript - 将加密浏览器添加到 Gatsby 项目
- python - 使用 cx_Freeze 创建 .msi 安装程序 -- 安装时显示消息
- python - 如何剥离 Python 列表中的元组
- git - .xlsx 文件中止 git restore 命令并生成 index.lock 文件
- javascript - 我们可以在对字符串数组进行排序时实现以下行为吗?
- node.js - 为什么要在复制 package.json 后复制 dot dot?
- javascript - 为什么只有单击两次按钮才写入js cookie?