Given this column type:
# schema.db
create_table "users", force: :cascade do |t|
..
t.jsonb "details", array: true
...
end
How can I remove a value by its index? My attempt ends up saving nil
at the index.
u = User.find(1).details
=> [{"group"=>[{"type"=>"website", "value"=>"https://www.stackoverflow.com/"}, {"type"=>"phone", "value"=>"212 111 1212"}]}, {"group"=>[{"type"=>nil, "value"=>nil}]}]
u.details[1] = nil
u.save
=> ... }]}, nil]>
CodePudding user response:
Use Array.delete_at(index)
method
u = User.find(1).details
=> [{"group"=>[{"type"=>"website", "value"=>"https://www.stackoverflow.com/"}, {"type"=>"phone", "value"=>"212 111 1212"}]}, {"group"=>[{"type"=>nil, "value"=>nil}]}]
u.delete_at(1)
u.save
=> ... }]}]>
You can even delete the element from nested array too
u = User.find(1).details
=> [{"group"=>[{"type"=>"website", "value"=>"https://www.stackoverflow.com/"}, {"type"=>"phone", "value"=>"212 111 1212"}]}, {"group"=>[{"type"=>nil, "value"=>nil}]}]
u["group"].delete_at(2)
u.save
=> ... }]}]>