【问题标题】:How to update json field's key name in rails using postgresql or activerecord?如何使用 postgresql 或 activerecord 在 Rails 中更新 json 字段的键名?
【发布时间】:2020-12-23 03:32:22
【问题描述】:

我有一个名为cart 的表,其中items 属于json 类型。购物车中的值如下 3 个示例:

1. Cart(id: 1, name: 'Test', items: [{'desc'=>'First','names'=>'First'}, {'desc'=>'Second','names'=>'Second'}])
2. Cart(id: 2, name: 'Test', items: [{'desc'=>'First','names'=>'First'}, {'desc'=>'Second','names'=>'Second'}])
3. Cart(id: 3, name: 'Test', items: [{'desc'=>'First','name'=>'First'}, {'desc'=>'Second','name'=>'Second'}])

如何更新所有项目键以在 rails 中使用 name 键而不是 names?这样就变成了:

1. Cart(id: 1, name: 'Test', items: [{'desc'=>'First','name'=>'First'}, {'desc'=>'Second','name'=>'Second'}])
2. Cart(id: 2, name: 'Test', items: [{'desc'=>'First','name'=>'First'}, {'desc'=>'Second','name'=>'Second'}])
3. Cart(id: 3, name: 'Test', items: [{'desc'=>'First','name'=>'First'}, {'desc'=>'Second','name'=>'Second'}])

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord


    【解决方案1】:

    我认为这样的事情应该可行:

    ActiveRecord::Base.connection.execute <<-SQL
      UPDATE cart t1
      SET items = (
        SELECT json_agg(
          el :: jsonb - 'names' || jsonb_build_object('name', el -> 'names')
        ) FROM cart t2, jsonb_array_elements(t2.items) as el
        WHERE t1.id = t2.id
      )
    SQL
    

    【讨论】:

      【解决方案2】:

      首先获取所有记录:

      all_carts = Cart.all

      #<:relation id: name: items:>

      然后循环每条记录并更改json键:

      all_carts.each do |cart|
        jitems = JSON.parse(cart.items) # ---> [{"desc"=>"First", "names"=>"First"}, {"desc"=>"Second", "names"=>"Second"}] 
        jitems.each { |it| it['name'] = it['names']; it.delete('names') } # ---> [{"desc"=>"First", "name"=>"First"}, {"desc"=>"Second", "name"=>"Second"}] 
        cart.items = jitems.to_json # ---> "[{\"desc\":\"First\",\"name\":\"First\"},{\"desc\":\"Second\",\"name\":\"Second\"}]"
        cart.save
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多