ruby-on-rails 将SQL结果转换为ActiveRecord关系

eivgtgni  于 9个月前  发布在  Ruby
关注(0)|答案(1)|浏览(82)

在下文中,

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

字符串
“sql”字符串是对返回表的db函数的调用。
我可以做些什么来让@records成为一个ActiveRecord关系,这样我就可以使用典型的关系方法/语法,如

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

h9a6wy2h

h9a6wy2h1#

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

字符串

相关问题