[英]Ruby on rails active record: update a field by another field in the same record using update_all
[英]Active Record Update All JSON Field
所以我有一个模型Item
,它有一个巨大的 postgresql JSON 字段,称为properties
。 大多数时候不需要查询或更改此字段,但是我们将price
存储在此字段中。
我目前正在编写一个更新这个price
的脚本,但是只有几个唯一的prices
和数千个Items
,所以为了节省时间,我有一个每个唯一price
的Items
列表,我正在尝试全部更新:
Item.where(id: items).update_all("properties->>'price' = #{unique_price}")
但这给了我:
syntax error at or near "->>"
有没有办法使用 update all 来更新 postgres JSON 字段中的字段?
您需要使用jsonb_set()
函数,这是一个示例:
Item.where(id: items).
update_all(
"properties = jsonb_set(properties, '{price}', to_json(#{unique_price}::int)::jsonb)"
)
这将保留所有值并仅更新一个键。
阅读 文档
你也可以这样做
Item.where(id: items).each do |item|
properties = item.properties
item.update(properties: properties.merge({
price: unique_price
}))
end
关键字merge
将覆盖与新值一起提供的键的值,即 unique_price
合并文档在这里
我根据@Philidor 的建议提出的想法非常相似,但具有动态绑定:
assignment = ["field = jsonb_set(field, '{ name_of_the_key }', ?)", value.to_json]
scope.update_all(scope.model.sanitize_sql_for_assignment(assignment))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.