【问题标题】:How to list of all the tables defined for the database when using active record?使用活动记录时如何列出为数据库定义的所有表?
【发布时间】:2010-09-14 08:08:25
【问题描述】:

使用活动记录时如何获取为数据库定义的所有表的列表?

【问题讨论】:

    标签: activerecord


    【解决方案1】:

    致电ActiveRecord::ConnectionAdapters::SchemaStatements#tables。此方法在 MySQL 适配器中未记录,但在 PostgreSQL 适配器中记录。 SQLite/SQLite3 也实现了该方法,但未记录。

    >> ActiveRecord::Base.connection.tables
    => ["accounts", "assets", ...]
    

    请参阅activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21,以及此处的实现:

    【讨论】:

    • 该列表还包括schema_migrations 表。请注意。谢谢:)
    • ActiveRecord::Base.connection 可能已被弃用? apidock.com/rails/ActiveRecord/Base/connection 我没有看到 ActiveRecord::Base.connection.tables 列在那里。
    【解决方案2】:

    根据前两个答案,您可以这样做:

    ActiveRecord::Base.connection.tables.each do |table|
      next if table.match(/\Aschema_migrations\Z/)
      klass = table.singularize.camelize.constantize      
      puts "#{klass.name} has #{klass.count} records"
    end
    

    列出每个抽象表的模型,以及记录的数量。

    【讨论】:

    • 对于单行狂热者(没有增加正则表达式表匹配的安全性):(ActiveRecord::Base.connection.tables - ['schema_migrations']).map {|t| "#{t.classify} 有 #{t.classify.constantize.count} 条记录" }
    • 为什么在这里使用正则表达式? “next if table == 'schema_migrations'”不是也能正常工作吗?
    【解决方案3】:

    Rails 5.2

    的更新

    对于 Rails 5.2,您还可以使用 ApplicationRecord 来获取带有表名称的 Array。只是,正如imechemi 所提到的,请注意,此方法还将在该数组中返回 ar_internal_metadataschema_migrations

    ApplicationRecord.connection.tables
    

    【讨论】:

      【解决方案4】:

      似乎应该有更好的方法,但这是我解决问题的方法:

      Dir["app/models/*.rb"].each do |file_path|
        require file_path # Make sure that the model has been loaded.
      
        basename  = File.basename(file_path, File.extname(file_path))
        clazz     = basename.camelize.constantize
      
        clazz.find(:all).each do |rec|
          # Important code here...
        end
      end
      

      此代码假定您遵循类和源代码文件的标准模型命名约定。

      【讨论】:

      • 它还假设您的 app/models/ 中的所有内容都是活动记录模型
      【解决方案5】:

      不知道活动记录,但这里有一个简单的查询:

      选择表名 来自 INFORMATION_SCHEMA.Tables 其中 TABLE_TYPE = '基表'

      【讨论】:

        猜你喜欢
        • 2015-03-19
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 1970-01-01
        • 2016-12-31
        • 2023-03-28
        • 2010-10-24
        相关资源
        最近更新 更多