7

When running a mysql query with ActiveRecord with Class.connection.execute('query here'), the result is an array, as opposed to a hash in postgres. This is tested with both mysql and mysql2 adapters, even though the default for mysql2 is to return the query result as a hash.

How can I get ActiveRecord to change the configuration options on the connection to return query results as a hash? Can I just not use ActiveRecord for this and I should use the raw mysql2 client?

Solomon
  • 6,145
  • 3
  • 25
  • 34
  • possible duplicate of [Why does Rails 3 with Mysql2 Gem ActiveRecord::Base.connection.execute(sql) return Array not Hash?](http://stackoverflow.com/questions/5760100/why-does-rails-3-with-mysql2-gem-activerecordbase-connection-executesql-retu) – sebkkom Oct 28 '14 at 10:42

1 Answers1

26

I had a similar problem and I found the solution on this answer:

You can do data = Class.connection.exec_query('query here') to get an ActiveRecord::Result

Then, you can do data.first for a hash, or use any of the other methods mentioned in the docs.

Community
  • 1
  • 1
sebkkom
  • 1,426
  • 17
  • 31