0

I have a ruby script, a postgres database and I use the Sequel gem to connect to the database.

I want to store and retrieve records, where some of the column values are arrays (set to text[] as data type). I therefore load the pg_array extension for sequel.

I create a hash {id: 1, key1: Sequel.pg_array(["lorem ipsum", "caesar", "quidquid id est, timeo danaos"])}

I can insert the hash through table.insert hash and it creates the correct looking record.

 id |                          key1                          
----+--------------------------------------------------------
 1  | {"lorem ipsum",caesar,"quidquid id est, timeo danaos"}

Based on this favourable result I deduce that the database, the sequel gem and the pg_array extension are all set up correctly.

However, when I retrieve the record via sequel again with advisers.where(id: 1).all I get this

[{:id => 1, :key1 => "{\"lorem ipsum\",caesar,\"quidquid id est, timeo danaos\"}"}]

The value of :key1 is returned as String. I can't make heads or tails of the documentation. Does anyone have a way to turn this directly back into the array it started out as: ["lorem ipsum", "caesar", "quidquid id est, timeo danaos"]?

Much appreciated from a total newbie

2 Answers 2

2

This is usually handled when you load the pg_array extension into your Sequel::Database instance. Maybe you just loaded the pg_array extension file without loading it into your Sequel::Database instance. You might have done:

Sequel.extension :pg_array

instead of:

DB.extension :pg_array

You need to load the pg_array extension into your Sequel::Database instance for retrieved values to be array-like objects and not strings.

Sign up to request clarification or add additional context in comments.

Comments

0

Check this, add following in your model

serialize :key1, Array

2 Comments

Thanks for the quick reply. I am not using Rails, so I'm not sure this applies. I can create a model, but it will not be able to inherit from ActiveRecord::Base as per your link.
as expected I get the following error following your solution: (undefined method 'serialize' for Adviser:Class). This is because my model cannot inherit from ActiveRecors, as I don't use rails in this setup.

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.