ActiveRecord: List columns in table from console

Solution 1:

This will list the column_names from a table

Model.column_names
e.g. User.column_names

Solution 2:

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}"
  end
end

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

Solution 3:

Using rails three you can just type the model name:

> User
gives:
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)
=> nil
irb(main):003:0> User
User(id: integer, name: string, email: string, etc...)