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

后端 未结 6 1745
忘了有多久
忘了有多久 2020-12-02 04:30

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

相关标签:
6条回答
  • 2020-12-02 04:38

    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'

    0 讨论(0)
  • 2020-12-02 04:42

    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" }
    
    0 讨论(0)
  • 2020-12-02 04:49

    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.

    0 讨论(0)
  • 2020-12-02 04:54

    Run this:

    Rails.application.eager_load! 
    

    Then

    ActiveRecord::Base.descendants
    

    To return a list of models/tables

    0 讨论(0)
  • 2020-12-02 04:57

    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.

    0 讨论(0)
  • 2020-12-02 04:59

    Its a start, it can list:

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

    Looking some more...

    0 讨论(0)
提交回复
热议问题