活动记录更新所有JSON字段

时间:2018-08-02 15:18:38

标签: ruby-on-rails postgresql activerecord

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

我目前正在编写更新此price的脚本,但是只有少数几个唯一的prices和数千个Items,所以为了节省时间,我列出了{每个唯一的Items的{​​1}},我正在尝试全部更新:

price

但这给了我:

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

是否可以使用全部更新来更新postgres JSON字段中的字段?

2 个答案:

答案 0 :(得分:1)

您需要使用jsonb_set()功能,此处是示例

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

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

阅读documentation

答案 1 :(得分:1)

您也可以这样做

Item.where(id: items).each do |item|
  properties = item.properties
  item.update(properties: properties.merge({
    price: unique_price
  }))
end

关键字merge将覆盖新值(即unique_price)提供的键的值

合并文档为here

相关问题