如何从 Rails/Postgres 中的 JSONB 数组列中删除值?

How do I remove a value from a JSONB array column in Rails/Postgres?

给定此列类型:

# schema.db
create_table "users", force: :cascade do |t|
  ..
  t.jsonb "details", array: true
  ...
end

如何通过索引删除一个值?我的尝试最终在索引处保存 nil

u = User.find(1).details
=> [{"group"=>[{"type"=>"website", "value"=>"https://www.whosebug.com/"}, {"type"=>"phone", "value"=>"212 111 1212"}]}, {"group"=>[{"type"=>nil, "value"=>nil}]}]
u.details[1] = nil
u.save
=> ... }]}, nil]>

使用Array.delete_at(index)方法

u = User.find(1).details
=> [{"group"=>[{"type"=>"website", "value"=>"https://www.whosebug.com/"}, {"type"=>"phone", "value"=>"212 111 1212"}]}, {"group"=>[{"type"=>nil, "value"=>nil}]}]
u.delete_at(1)
u.save
=> ... }]}]>

您甚至可以从嵌套数组中删除元素

u = User.find(1).details
=> [{"group"=>[{"type"=>"website", "value"=>"https://www.whosebug.com/"}, {"type"=>"phone", "value"=>"212 111 1212"}]}, {"group"=>[{"type"=>nil, "value"=>nil}]}]
u["group"].delete_at(2)
u.save
=> ... }]}]>