Answers:
致电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
和此处的实现:
根据前面的两个答案,您可以执行以下操作:
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
列出抽象表的每个模型以及记录数。
似乎应该有更好的方法,但是这是我解决问题的方法:
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
此代码假定您遵循类和源代码文件的标准模型命名约定。
schema_migrations
表。请注意。谢谢:)