活动记录更新所有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.
读取文档