Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: List columns in table from console

This will list the column_names from a table

Model.column_names
e.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}"
  end
end

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


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...)

If you are comfortable with SQL commands, you can enter your app's folder and run rails db, which is a brief form of rails dbconsole. It will enter the shell of your database, whether it is sqlite or mysql.

Then, you can query the table columns using sql command like:

pragma table_info(your_table);

You can run rails dbconsole in you command line tool to open sqlite console. Then type in .tables to list all the tables and .fullschema to get a list of all tables with column names and types.


complementing this useful information, for example using rails console o rails dbconsole:

Student is my Model, using rails console:

$ rails console
> Student.column_names
 => ["id", "name", "surname", "created_at", "updated_at"] 

> Student
 => Student(id: integer, name: string, surname: string, created_at: datetime, updated_at: datetime)

Other option using SQLite through Rails:

$ rails dbconsole

sqlite> .help

sqlite> .table
ar_internal_metadata  relatives             schools             
relationships         schema_migrations     students 

sqlite> .schema students
CREATE TABLE "students" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "surname" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);

Finally for more information.

sqlite> .help

Hope this helps!


  • To list the columns in a table I usually go with this:
    Model.column_names.sort.
    i.e. Orders.column_names.sort

    Sorting the column names makes it easy to find what you are looking for.

  • For more information on each of the columns use this:
    Model.columns.map{|column| [column.name, column.sql_type]}.to_h.

This will provide a nice hash. for example:

{
   id => int(4),
   created_at => datetime
}