Why does Rails 3 with Mysql2 Gem ActiveRecord::Base.connection.execute(sql) return Array not Hash?

♀尐吖头ヾ 提交于 2019-12-02 17:43:09

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

I faced a similar issue a while back and found this to work:

result = ActiveRecord::Base.connection.execute(sql) 
result.each(:as => :hash) do |row| 
   row["field"] 
end

edit: you could also use the select_all method of the connection object that returns a hash

instead of

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

do

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

And that'll do exactly what you want. In particular,

results.first

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

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

table header

results.first.keys.each do |key|
 key
end

table data

results.each do |result| %>
  result.values.each do |value| %>
    value
  end
end

Improving dan's answer, Rails 3.2.8 won't accept RAILS_ENV.


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!