ActiveRecord: List columns in table from console

SqlRuby on-RailsRuby on-Rails-3Activerecord

Sql Problem Overview


I know that you can ask ActiveRecord to list tables in console using:

ActiveRecord::Base.connection.tables

Is there a command that would list the columns in a given table?

Sql Solutions


Solution 1 - Sql

This will list the column_names from a table

Model.column_names
e.g. User.column_names

Solution 2 - Sql

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 - Sql

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

Solution 4 - Sql

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

Solution 5 - Sql

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.

Solution 6 - Sql

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!

Solution 7 - Sql

  • 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
}

Solution 8 - Sql

For a more compact format, and less typing just:

Portfolio.column_types 

Solution 9 - Sql

I am using rails 6.1 and have built a simple rake task for this.

You can invoke this from the cli using rails db:list[users] if you want a simple output with field names. If you want all the details then do rails db:list[users,1].

I constructed this from this question https://stackoverflow.com/questions/825748/how-to-pass-command-line-arguments-to-a-rake-task about passing command line arguments to rake tasks. I also built on @aaron-henderson's answer above.

# run like `rails db:list[users]`, `rails db:list[users,1]`, `RAILS_ENV=development rails db:list[users]` etc
namespace :db do
  desc "list fields/details on a model"
  task :list, [:model, :details] => [:environment] do |task, args|
    model = args[:model]
    if !args[:details].present?
      model.camelize.constantize.column_names.each do |column_name|
        puts column_name
      end
    else
      ActiveRecord::Base.connection.tables.each do |table_name|
        next if table_name != model.underscore.pluralize
        ActiveRecord::Base.connection.columns(table_name).each do |c|
          puts "Name: #{c.name} | Type: #{c.type} | Default: #{c.default} | Limit: #{c.limit} | Precision: #{c.precision} | Scale: #{c.scale} | Nullable: #{c.null} "
        end
      end
    end
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - SqlPravinView Answer on Stackoverflow
Solution 2 - SqlAaron HendersonView Answer on Stackoverflow
Solution 3 - SqlYuleView Answer on Stackoverflow
Solution 4 - Sqlgm2008View Answer on Stackoverflow
Solution 5 - SqlcodeepicView Answer on Stackoverflow
Solution 6 - SqlGamalielView Answer on Stackoverflow
Solution 7 - SqlcsebryamView Answer on Stackoverflow
Solution 8 - SqlvalkView Answer on Stackoverflow
Solution 9 - SqlJay KilleenView Answer on Stackoverflow