将sql结果转换为ActiveRecord关系

时间:2018-04-10 18:24:47

标签: sql ruby-on-rails activerecord dbfunctions

以下,

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

“sql”字符串是对返回表的db函数的调用。 这行代码返回#<ActiveRecord::Result:0x007fd90ba87460 @columns=["zip_code", "county", ..], @rows=[[94121, "San Francisco", ..], [94110, "San Francisco", ..], ..]

我可以做些什么来让@records成为ActiveRecord关系,这样我就可以使用典型的关系方法/语法,如

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

1 个答案:

答案 0 :(得分:1)

此类封装从任何数据库连接适配器上调用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