Active Record Update All JSON Field

大兔子大兔子 提交于 2019-12-12 14:02:56

问题


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}")

But this gives me:

syntax error at or near "->>"

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


回答1:


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.

Read documentation




回答2:


You can also do this

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

The keyword merge will override the value of the key provided with the new value ie unique_price

Merge documentation is here



来源:https://stackoverflow.com/questions/51657123/active-record-update-all-json-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!