4

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
Tim Koelkebeck
  • 795
  • 2
  • 9
  • 18

1 Answers1

2

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
fool-dev
  • 7,671
  • 9
  • 40
  • 54
  • beautiful answer, thank you! In my pre-question research I came across find_by_sql but did not realize it could be used this way. – Tim Koelkebeck Apr 10 '18 at 22:15
  • it suits the author's needs because they only wanted to use `each` which works on an array, but I was interested in getting an ARRelation so I could use `where`, which is sort of what they asked _"What can I do to get @records to be an ActiveRecord relation instead, so that I can use typical relation methods"_ – ryan2johnson9 Dec 01 '22 at 04:22