0

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]>

1 Answer 1

1

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
=> ... }]}]>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.