rails support method for PSQL array values to ruby array?

Viewed 38

Pretty straight forward, not looking to reinvent the wheel but is there rails method that turns results from a PSQL array to a ruby array.

example

results = ActiveRecord::Base.connection.execute("select array_agg(id) from users;").to_a
# => [{"array_agg"=>"{1,2,3}"}]

thing.call(results[0]["array_agg"])
# => ["1", "2","3"]
1 Answers

ActiveRecord::Base.connection.execute returns PG::Result object

You need ActiveRecord::Result that have cast_values method (it uses deserialize under the hood)

exec_query does this job

ActiveRecord::Base.connection.exec_query("select array_agg(id) from users;").cast_values

# => [[1, 2, 3]]
Related