Home > OS >  rails support method for PSQL array values to ruby array?
rails support method for PSQL array values to ruby array?

Time:09-09

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
puts results => [{"array_agg"=>"{1,2,3}"}]

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

CodePudding user response:

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