ActiveRecord: List columns in table from console ActiveRecord: List columns in table from console ruby-on-rails ruby-on-rails

ActiveRecord: List columns in table from console


This will list the column_names from a table

Model.column_namese.g. User.column_names


This gets the columns, not just the column names and uses ActiveRecord::Base::Connection, so no models are necessary. Handy for quickly outputting the structure of a db.

ActiveRecord::Base.connection.tables.each do |table_name|  puts table_name  ActiveRecord::Base.connection.columns(table_name).each do |c|     puts "- #{c.name}: #{c.type} #{c.limit}"  endend

Sample output: http://screencast.com/t/EsNlvJEqM


Using rails three you can just type the model name:

> Usergives:User(id: integer, name: string, email: string, etc...)

In rails four, you need to establish a connection first:

irb(main):001:0> User=> User (call 'User.connection' to establish a connection)irb(main):002:0> User.connection; nil #call nil to stop repl spitting out the connection object (long)=> nilirb(main):003:0> UserUser(id: integer, name: string, email: string, etc...)