ActiveRecord:从控制台列出表中的列

发布于 2024-10-30 12:21:33 字数 134 浏览 1 评论 0原文

我知道您可以要求 ActiveRecord 使用以下命令在控制台中列出表:

ActiveRecord::Base.connection.tables

是否有一个命令可以列出给定表中的列?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

甜尕妞 2024-11-06 12:21:33

这将列出表中的column_names

Model.column_names
e.g. User.column_names

This will list the column_names from a table

Model.column_names
e.g. User.column_names
可可 2024-11-06 12:21:33

这会获取列,而不仅仅是列名称,并使用 ActiveRecord::Base::Connection,因此不需要任何模型。方便快速输出数据库的结构。

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

示例输出:http://screencast.com/t/EsNlvJEqM

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

盗心人 2024-11-06 12:21:33

使用 Rails 3,您只需键入型号名称即可:

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

在 Rails 4 中,您需要首先建立连接:

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

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...)
杀手六號 2024-11-06 12:21:33

补充这些有用的信息,例如使用rails控制台或rails dbconsole:

学生是我的模型,使用rails控制台:

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

通过Rails使用SQLite的其他选项:

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

最后了解更多信息。

sqlite> .help

希望这有帮助!

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!

末骤雨初歇 2024-11-06 12:21:33

如果您熟悉 SQL 命令,则可以进入应用的文件夹并运行 rails db,它是 rails dbconsole 的简短形式。它会进入你数据库的shell,无论是sqlite还是mysql。

然后,您可以使用 sql 命令查询表列,例如:

pragma table_info(your_table);

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);
因为看清所以看轻 2024-11-06 12:21:33

您可以在命令行工具中运行rails dbconsole来打开sqlite控制台。然后输入 .tables 以列出所有表,并输入 .fullschema 以获取包含列名称和类型的所有表的列表。

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.

浅笑依然 2024-11-06 12:21:33
  • 要列出表中的列,我通常会这样做:
    Model.column_names.sort
    即 Orders.column_names.sort

    对列名称进行排序可以轻松找到您要查找的内容。

  • 有关每一列的更多信息,请使用:
    Model.columns.map{|列| [column.name, column.sql_type]}.to_h。

这将提供一个很好的哈希值。
例如:

{
   id => int(4),
   created_at => datetime
}
  • 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
}
無心 2024-11-06 12:21:33

对于更紧凑的格式,并减少键入:

Portfolio.column_types 

For a more compact format, and less typing just:

Portfolio.column_types 
嘴硬脾气大 2024-11-06 12:21:33

我正在使用 Rails 6.1 并为此构建了一个简单的 rake 任务。

如果您想要带有字段名称的简单输出,您可以使用 rails db:list[users] 从 cli 调用它。如果您需要所有详细信息,请执行 rails db:list[users,1]

我从这个问题 如何传递命令行参数构建了这个关于将命令行参数传递给 rake 任务的 rake 任务。我还建立在@aaron-henderson 上面的答案的基础上。

# 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

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 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文