为什么使用Mysql2的Rails 3 Gem ActiveRecord :: Base.connection.execute(sql)返回Array不是哈希? [英] Why does Rails 3 with Mysql2 Gem ActiveRecord::Base.connection.execute(sql) return Array not Hash?

查看:103
本文介绍了为什么使用Mysql2的Rails 3 Gem ActiveRecord :: Base.connection.execute(sql)返回Array不是哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将应用程序升级到Rails 3.我决定使用mysql2 gem。在应用程序中有一些遗留代码可以调用,如:

  results = ActiveRecord :: Base.connection.execute(sql)

在2.3.x版本中,它使用

  results.each_hash do | row | 
...

但是使用gem mysql2,结果是 Mysql2 :: Result ,它只有一个每个方法。检查了文档,并且他们指定的结果应该是字段名称上的哈希键。太棒了!



但实际上,它是 Array ,而不是哈希 code $。

当我使用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

这是丑陋的罪过。 p>

有人如何让它返回一个Hash而不是Array?

解决方案

如果您只是想重复使用 database.yml 配置,您可以这样做:

  config = ActiveRecord :: Base.configurations [RAILS_ENV] .symbolize_keys 
conn = Mysql2 :: Client.new(config)
conn.query(select * from users) .each do | user |
#用户应该是一个哈希
结束


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?

解决方案

If you just want to reuse the database.yml configuration, you can do this:

config = ActiveRecord::Base.configurations[RAILS_ENV].symbolize_keys
conn = Mysql2::Client.new(config)
conn.query("select * from users").each do |user|
  # user should be a hash
end

这篇关于为什么使用Mysql2的Rails 3 Gem ActiveRecord :: Base.connection.execute(sql)返回Array不是哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆