Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby PG gem select field in array format

I have a postgresql field that stores a 4-element array. I want to select the value of that field, but it's coming back as a string:

{43.690916,-79.396774,43.700845,-79.37125}  

I would assume that the gem would have known the format of that field and returned an array but I am wrong.

How can I get this into an array without going through string methods? That would seem like a hack. Moving from four individual float fields to a single array field with associated methods, I thought would make records easier to access.

There was no migration, and restrictive to assume this is in Rails, which it is not. Here is the structure:

Column   |          Type          | Collation | Nullable |                  Default
-----------+------------------------+-----------+----------+-------------------------------------------
 loc_id    | integer                |           | not null | nextval('mjtable_loc_id_seq'::regclass)
 locname   | character varying(255) |           |          |
 locbounds | double precision[]     |           |          |
like image 945
Rich_F Avatar asked May 12 '26 12:05

Rich_F


1 Answers

In Postgres, array is still a string in the database so you will only have a string and you would need to deal with that as such.

conn = PG.connect( dbname: 'pgarray_development') # or whatever db name
data = conn.exec('SELECT * FROM foos').entries
=> [{"id"=>"1", "coords"=>"{1.0,2.0,3.0,4.0}"]
data.first['coords'].class
=>String

But you can do this

conn.type_map_for_results = PG::BasicTypeMapForResults.new conn
conn.exec("select coords::float[] from foos").values
=> [[1.0, 2.0, 3.0, 4.0]]

There are probably other ways to use type casts, see https://bitbucket.org/ged/ruby-pg/wiki/Home

like image 177
lacostenycoder Avatar answered May 15 '26 01:05

lacostenycoder