【发布时间】:2010-09-14 08:08:25
【问题描述】:
使用活动记录时如何获取为数据库定义的所有表的列表?
【问题讨论】:
标签: activerecord
使用活动记录时如何获取为数据库定义的所有表的列表?
【问题讨论】:
标签: activerecord
致电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.tables.each do |table|
next if table.match(/\Aschema_migrations\Z/)
klass = table.singularize.camelize.constantize
puts "#{klass.name} has #{klass.count} records"
end
列出每个抽象表的模型,以及记录的数量。
【讨论】:
Rails 5.2
的更新
对于 Rails 5.2,您还可以使用 ApplicationRecord 来获取带有表名称的 Array。只是,正如imechemi 所提到的,请注意,此方法还将在该数组中返回 ar_internal_metadata 和 schema_migrations。
ApplicationRecord.connection.tables
【讨论】:
似乎应该有更好的方法,但这是我解决问题的方法:
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
此代码假定您遵循类和源代码文件的标准模型命名约定。
【讨论】:
不知道活动记录,但这里有一个简单的查询:
选择表名 来自 INFORMATION_SCHEMA.Tables 其中 TABLE_TYPE = '基表'
【讨论】: