gpt4 book ai didi

sql - 将sql结果转换为ActiveRecord关系

转载 作者:行者123 更新时间:2023-12-04 16:03:37 24 4
gpt4 key购买 nike

在下面的,

@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

最佳答案

该类封装了调用 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

关于sql - 将sql结果转换为ActiveRecord关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49760603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com