为什么 Rails 3 与 Mysql2 Gem ActiveRecord::Base.connection.execute(sql) 返回数组而不是哈希?
我正在将应用程序升级到 Rails 3。我决定使用 mysql2 gem。应用程序中有一些遗留代码进行如下调用:
results = ActiveRecord::Base.connection.execute(sql)
在 2.3.x 版本中,它使用了
results.each_hash do |row|
...
但是对于 gem mysql2,结果是类型 Mysql2::Result
,它只有一个 each< /代码> 方法。检查了文档,他们指定结果应该是基于字段名称的哈希值。伟大的!
但实际上,它是一个Array
,而不是Hash
。
当我使用 Rails 控制台并实例化我自己的 Mysql2::Client
并在那里运行查询时,结果是一个 Hash
,这就是我想。
在rails应用程序中,我认为最好使用ActiveRecord::Base.connection
,因为它是使用database.yml中的选项实例化的。
请注意,不幸的是结果没有映射到模型,所以我不能使用它。
例如,我现在所做的是:
result = ActiveRecord::Base.connection.execute(sql)
field_index = result.fields.index("field")
result.each do |row|
row[field_index]
end
这是丑陋的。
有谁知道如何让它返回哈希而不是数组吗?
I'm in the process of upgrading an application to Rails 3. I've decided to go with the mysql2 gem. There's some legacy code in the app that makes calls like:
results = ActiveRecord::Base.connection.execute(sql)
In the 2.3.x version, it used
results.each_hash do |row|
...
But with gem mysql2, results is type Mysql2::Result
, which has only an each
method. Checked the docs and they specify results should be a hash keyed on field name. Great!
But in fact, it is an Array
, not a Hash
.
When I use the rails console and instantiate my own Mysql2::Client
and run the query there, the results are a Hash
, which is what I want.
In the rails application, I think it's better to use ActiveRecord::Base.connection
, since it's been instantiated with options from database.yml.
Note, unfortunately the result does not map to a model, so I can't use that.
What I've done for now is, for example:
result = ActiveRecord::Base.connection.execute(sql)
field_index = result.fields.index("field")
result.each do |row|
row[field_index]
end
Which is ugly as sin.
Does anyone how I can get it to return a Hash instead of Array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不久前遇到了类似的问题,发现这可行:
编辑:您还可以使用 返回哈希的连接对象的select_all方法
I faced a similar issue a while back and found this to work:
edit: you could also use the select_all method of the connection object that returns a hash
而不是
do
这将完全按照您的要求进行。特别是,
将是一个散列,等等。
感谢@_fx 解决了这个问题!
有关更多信息,请参阅 http://api.rubyonrails.org /classes/ActiveRecord/ConnectionAdapters/Mysql2Adapter.html#method-i-exec_query
instead of
do
And that'll do exactly what you want. In particular,
will be a hash, and so on.
Thanks to @_fx for figuring this out!
For more, see http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Mysql2Adapter.html#method-i-exec_query
如果您只想重用
database.yml
配置,您可以这样做:If you just want to reuse the
database.yml
configuration, you can do this:表头
表数据
table header
table data
改进dan的答案,Rails 3.2.8不会接受RAILS_ENV。
Improving dan's answer, Rails 3.2.8 won't accept RAILS_ENV.