活动记录更新所有JSON字段 [英] Active Record Update All JSON Field

查看:102
本文介绍了活动记录更新所有JSON字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个模型 Item ,该模型具有一个名为 properties 的大型PostgreSQL JSON字段。在大多数情况下,无需查询或更改此字段,但是我们在此字段中存储 price

So I have a model Item that has a huge postgresql JSON field called properties. Most of the time this field does not need to be queried on or changed, however we store price in this field.

我目前正在编写一个脚本,用于更新此价格,但是只有几个独特的价格和数千个商品,所以为了节省时间,我列出了商品为每个唯一的价格,而我尝试全部更新:

I'm currently writing a script that updates this price, but there's only a few unique prices and thousands of Items so in order to save time I have a list of Items for each unique price and I'm attempting to do an update all:

Item.where(id:items).update_all( properties->>'price'=#{unique_price})

但是,这给了我:

->>或附近的语法错误

是否可以使用update all更新postgres JSON字段中的字段?

Is there a way to use update all to update a field in a postgres JSON field?

推荐答案

您需要使用 jsonb_set()函数,此处是示例

You need to use jsonb_set() function, here is an example:

Item.where(id: items).
     update_all(
       "properties = jsonb_set(properties, '{price}', to_json(#{unique_price}::int)::jsonb)"
     )

这将保留所有值并仅更新一个键。

This would preserve all values and update only one key.

读取< a href = https://www.postgresql.org/docs/9.5/static/functions-json.html rel = noreferrer>文档

这篇关于活动记录更新所有JSON字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆