In the following,
@records = ActiveRecord::Base.connection.exec_query(sql)
The "sql" string is a call to a db function that returns a table.
This line of code returns #<ActiveRecord::Result:0x007fd90ba87460 @columns=["zip_code", "county", ..], @rows=[[94121, "San Francisco", ..], [94110, "San Francisco", ..], ..]
What can I do to get @records to be an ActiveRecord relation instead, so that I can use typical relation methods/syntax like
@records.each do |r| r.county, r.zip_code end
This class encapsulates a result returned from calling exec_query
on any database connection adapter. For example:
sql = 'SELECT id, zip_code, county FROM records'
@records = ActiveRecord::Base.connection.exec_query(sql)
# Get the column names of the result:
@records.columns
# => ["id", "zip_code", "county"]
# Get the record values of the result:
@records.rows
# => [[1, "94121", "San Francisco"],
[2, "94110", "San Francisco"],
...
]
# Get an array of hashes representing the result (column => value):
@records.to_hash
# => [{"id" => 1, "zip_code" => "94121", "county" => "San Francisco"},
{"id" => 2, "zip_code" => "94110", "county" => "San Francisco"},
...
]
# ActiveRecord::Result also includes Enumerable.
@records.each do |row|
puts row['zip_code'] + " " + row['county']
end