Ruby-on-rails Rails:如何使用 Rails 控制台列出数据库表/对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2098131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: How to list database tables/objects using the Rails console?
提问by rtfminc
I was wondering if you could list/examine what databases/objects are available to you in the Rails console. I know you can see them using other tools, I am just curious. Thanks.
我想知道您是否可以在 Rails 控制台中列出/检查哪些数据库/对象可用。我知道您可以使用其他工具看到它们,我只是很好奇。谢谢。
回答by cwninja
You are probably seeking:
您可能正在寻找:
ActiveRecord::Base.connection.tables
and
和
ActiveRecord::Base.connection.columns('projects').map(&:name)
You should probably wrap them in shorter syntax inside your .irbrc.
您可能应该将它们以更短的语法包装在您的.irbrc.
回答by hamster ham
I hope my late answer can be of some help.
This will go to rails database console.
我希望我迟到的回答能有所帮助。
这将转到 rails 数据库控制台。
rails db
pretty print your query output
漂亮地打印您的查询输出
.headers on
.mode columns
(turn headers on and show database data in column mode )
Show the tables
显示表格
.table
'.help' to see help.
Or use SQL statements like 'Select * from cars'
'.help' 查看帮助。
或者使用 SQL 语句,如“从汽车中选择 *”
回答by DomQ
To get a list of all model classes, you can use ActiveRecord::Base.subclassese.g.
要获取所有模型类的列表,您可以使用ActiveRecord::Base.subclasses例如
ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }
回答by Ralf Rafael Frix
You can use rails dbconsoleto view the database that your rails application is using. It's alternative answer rails db. Both commands will direct you the command line interface and will allow you to use that database query syntax.
您可以使用rails dbconsole来查看 Rails 应用程序正在使用的数据库。这是替代答案rails db。这两个命令都将引导您进入命令行界面,并允许您使用该数据库查询语法。
回答by stevec
Run this:
运行这个:
Rails.application.eager_load!
Then
然后
ActiveRecord::Base.descendants
To return a list of models/tables
返回模型/表的列表
回答by rtfminc
Its a start, it can list:
它是一个开始,它可以列出:
models = Dir.new("#{RAILS_ROOT}/app/models").entries
Looking some more...
再看几...

