Skip to content

Instantly share code, notes, and snippets.

@terrafied
Last active January 2, 2016 12:58
Show Gist options
  • Save terrafied/8306489 to your computer and use it in GitHub Desktop.
Save terrafied/8306489 to your computer and use it in GitHub Desktop.
ActiveRecord to_a madness

Same console, same codebase, different database connections. Result: different object types returned.

Example classes

class User < ActiveRecord::Base
   ...
end

class Series < ActiveRecord::Base
   establish_connection postgres_database_hash
   ...
end

With a MySQL connection: Array of arrays

> User.connection.execute('SELECT * from users limit 2').to_a
   (211.0ms)  SELECT * from users limit 2
 => [[1, "jmetta", "jmetta@gmail.com"], [2, "johnmetta", "jmetta+test@gmail.com"]]

With a Postgres connection: Array of hashes

 > Series.connection.execute('SELECT * from series limit 2').to_a
    (107.1ms)  SELECT * from series limit 2
  => [{"id"=>"29", "enr_id"=>"114118", "ent_id"=>"164",}, {"id"=>"30", "enr_id"=>"114110", "ent_id"=>"164"}]

In short: WTH, ActiveRecord?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment