将 sql 个结果转换为 ActiveRecord 关系

convert sql results to ActiveRecord relation

在下面,

@records = ActiveRecord::Base.connection.exec_query(sql)

"sql" 字符串是对 returns 和 table 的数据库函数的调用。 这行代码returns#<ActiveRecord::Result:0x007fd90ba87460 @columns=["zip_code", "county", ..], @rows=[[94121, "San Francisco", ..], [94110, "San Francisco", ..], ..]

我该怎么做才能让@records 成为一个 ActiveRecord 关系,这样我就可以使用典型的关系 methods/syntax,比如

@records.each do |r| r.county, r.zip_code end

这个 class 封装了在任何数据库连接适配器上调用 exec_query 返回的结果。例如:

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