为什么使用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?
问题描述
我正在将应用程序升级到Rails 3.我决定使用mysql2 gem。在应用程序中有一些遗留代码可以调用,如:
results = ActiveRecord :: Base.connection.execute(sql)
在2.3.x版本中,它使用
results.each_hash do | row |
...
但是使用gem mysql2,结果是 Mysql2 :: Result
,它只有一个每个
方法。检查了文档,并且他们指定的结果应该是字段名称上的哈希键。太棒了!
但实际上,它是 当我使用rails控制台并实例化我自己的 在rails应用程序中,我认为最好使用 注意,不幸的是结果没有映射到模型,所以我不能使用它。 例如: 这是丑陋的罪过。 p> 有人如何让它返回一个Hash而不是Array? 如果您只是想重复使用 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: In the 2.3.x version, it used But with gem mysql2, results is type But in fact, it is an When I use the rails console and instantiate my own In the rails application, I think it's better to use 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: 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
这篇关于为什么使用Mysql2的Rails 3 Gem ActiveRecord :: Base.connection.execute(sql)返回Array不是哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Array
,而不是哈希 code $。
Mysql2 :: Client
并运行那里的查询,结果是 Hash
,这就是我想要的。
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
database.yml
配置,您可以这样做:
config = ActiveRecord :: Base.configurations [RAILS_ENV] .symbolize_keys
conn = Mysql2 :: Client.new(config)
conn.query(select * from users) .each do | user |
#用户应该是一个哈希
结束
results = ActiveRecord::Base.connection.execute(sql)
results.each_hash do |row|
...
Mysql2::Result
, which has only an each
method. Checked the docs and they specify results should be a hash keyed on field name. Great!Array
, not a Hash
.Mysql2::Client
and run the query there, the results are a Hash
, which is what I want.ActiveRecord::Base.connection
, since it's been instantiated with options from database.yml. result = ActiveRecord::Base.connection.execute(sql)
field_index = result.fields.index("field")
result.each do |row|
row[field_index]
end
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