Last Updated: March 09, 2019
·
7.554K
· robguilfoyle

How to get an array of values from PG::Result when using ActiveRecord::Base

Some time ago I wanted to use Google’s Visualization API in order to show some analytics. The problem I was having is ActiveRecord returns the results as a hash with the keys in every row (much like you would expect a hash to look like). Google’s Visualization API doesn’t allow that kind of data and needs it in a value only format:

The Bad:

{"course"=>"Introduction To Retirement Funds", "points"=>"7750"}
{"course"=>"Hedge funds", "points"=>"0"}
{"course"=>"Personal bankruptcy", "points"=>"0"}
{"course"=>"Mortgages", "points"=>"0"}
{"course"=>"Inflation scenarios", "points"=>"0"}

The Good:

[["Introduction To Retirement Funds", "7750"],
["Hedge funds", "0"],
["Personal bankruptcy", "0"],
["Mortgages", "0"],
["Inflation scenarios", "0"],
["Mutual funds and ETFs", "0"]]

ActiveRecord will return the first set above; however, if you simply add .values to the returned object you will get what you need. Like so:

ActiveRecord::Base.connection.execute("SELECT * FROM courses").values