ActiveRecord: List columns in table from console

前端 未结 8 1337
遥遥无期
遥遥无期 2020-12-22 23:21

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

ActiveRecord::Base.connection.tables

Is there a command that would li

相关标签:
8条回答
  • 2020-12-22 23:42

    This will list the column_names from a table

    Model.column_names
    e.g. User.column_names
    
    0 讨论(0)
  • 2020-12-22 23:43

    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.

    0 讨论(0)
  • 2020-12-22 23:44

    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

    0 讨论(0)
  • 2020-12-22 23:47

    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);
    
    0 讨论(0)
  • 2020-12-22 23:54

    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!

    0 讨论(0)
  • 2020-12-22 23:59

    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...)
    
    0 讨论(0)
提交回复
热议问题