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

匿名 (未验证) 提交于 2019-12-03 01:54:01

问题:

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.

回答1:

You are probably seeking:

ActiveRecord::Base.connection.tables 

and

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

You should probably wrap them in shorter syntax inside your .irbrc.



回答2:

I hope my late answer can be of some help.
This will go to rails database console.

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'



回答3:

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name } ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" } 


回答4:

You can use rails dbconsole to 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.



回答5:

Its a start, it can list:

models = Dir.new("#{RAILS_ROOT}/app/models").entries 

Looking some more...



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!