如何在CLI上显示活动记录表及其列?

时间:2018-12-11 01:23:35

标签: ruby activerecord terminal rails-activerecord

我是活动记录的新手,正在做表迁移。我想在终端上查看已迁移的表及其对应的列名。有人知道执行此操作的命令吗?

假设我有2张桌子猫和狗,是否有一个命令可以在CLI中显示类似这样的内容?

5020 11:34:15:398 debug1: subsystem: internal-sftp
5020 11:34:15:398 Starting session: forced-command (config) 'internal-sftp' for fred from ::1 port 54492 id 0
5020 11:34:15:711 debug1: Executing command: C:\\Program Files\\OpenSSH-Win64\\sftp-server.exe

3 个答案:

答案 0 :(得分:1)

有几种方法可以获取有关数据库的信息,但这应该可以从rails console开始工作:

ActiveRecord::Base.connection.tables.each do |table|
  next unless ActiveRecord.const_defined?(table.classify) && !table.match(/schema_migrations/)
  puts table.classify.to_s
  puts '-----'
  puts table.classify.constantize.column_names
  puts
  puts
end;

答案 1 :(得分:0)

  

您可能正在寻找:

     

ActiveRecord::Base.connection.tables

     

     

ActiveRecord::Base.connection.table_structure("projects")

参考Rails: How to list database tables/objects using the Rails console?

答案 2 :(得分:0)

如果您的目标只是在命令行上查看表结构,则可以打印db/schema.rb的内容,Rails在运行迁移时将其维护。该文件包括表名,列名和数据类型。它甚至包括索引。

在macOS或Linux上:cat db/schema.rb

在Windows上:type db/schema.rb