131

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

4

5 回答 5

270

打电话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以及此处的实现:

于 2008-10-01T00:34:18.077 回答
20

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

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

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

于 2013-01-11T11:00:44.680 回答
14

Rails 5.2的更新

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

ApplicationRecord.connection.tables
于 2018-06-22T15:00:19.757 回答
2

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

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

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

于 2008-09-30T23:07:38.770 回答
0

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

从 INFORMATION_SCHEMA.Tables 中选择 table_name,其中 TABLE_TYPE = 'BASE TABLE'

于 2008-09-30T18:57:38.433 回答