Question: Save from params to JSONB datatype column using Postgres


Save from params to JSONB datatype column using Postgres

Answers 0
Added at 2016-11-16 17:11

I'm kinda new working with JSONB datatype column and I'm having some trouble saving the data the way I'd like to my database in Ruby on Rails.

I'd like to save the data as follows:

col = [{"k1"=>"v1","k2"=>"v2"},[{"sk1"=>"sv1","sk2"=>"sv2"},{"sk1"=>"sv1","sk2"=>"sv2",...,{"sk1"=>"sv1","sk2"=>"sv2"}]]

So basically an Array that has 2 elements, first being a Hash, and second being an Array of n Hashes, not necessarily the same number between records.

I want to save like this because I want to be able to do something like:

x.col[1].each do |y|
  puts y["sk1"]

The data comes from a Form and I'm saving it directly from Params, and it's saving as follows:

{"0"=>{"k1"=>"v1", "k2"=>"v2"}, "1"=>{"0"=>{"sk1"=>"a", "sk2"=>"b"}, "1"=>{"sk1"=>"c", "sk2"=>"d"}}}

It saves exactly as the Params look like.

I'd like to get rid of the indexes, because I can't iterate through the inner Array to retrieve the data.

1) Is it possible to save the data the way I'd like?
2) How do I get rid of those indexes when I save the data to the database?
3) Is it a correct approach to doing this?
4) Essentially I need a hand on how to properly save data that comes from params into a JSONB datatype

Source Show
◀ Wstecz