How do I get a list of all the tables defined for the database when using active record?
5 Answers
Call ActiveRecord::ConnectionAdapters::SchemaStatements#tables
. This method is undocumented in the MySQL adapter, but is documented in the PostgreSQL adapter. SQLite/SQLite3 also has the method implemented, but undocumented.
>> ActiveRecord::Base.connection.tables
=> ["accounts", "assets", ...]
See activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21
, as well as the implementations here:
-
3The list also includes
schema_migrations
table. Just be aware. Thanks :) Feb 7, 2017 at 3:55 -
ActiveRecord::Base.connection may be deprecated ? apidock.com/rails/ActiveRecord/Base/connection I don't see ActiveRecord::Base.connection.tables listed there.– barlopMar 12, 2018 at 11:21
Based on the two previous answers, you could do:
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
to list every model that abstracts a table, with the number of records.
-
2for the single-line fanatics (without the added security of the regex table match): (ActiveRecord::Base.connection.tables - ['schema_migrations']).map {|t| "#{t.classify} has #{t.classify.constantize.count} records" } Jul 16, 2014 at 21:05
-
1Why do you use a regex here? Wouldn't "next if table == 'schema_migrations'" work just as well?– tbreierJun 10, 2016 at 17:32
An update for Rails 5.2
For Rails 5.2 you can also use ApplicationRecord
to get an Array
with your table' names. Just, as imechemi mentioned, be aware that this method will also return ar_internal_metadata
and schema_migrations
in that array.
ApplicationRecord.connection.tables
Keep in mind that you can remove ar_internal_metadata
and schema_migrations
from the array by calling:
ApplicationRecord.connection.tables - %w[ar_internal_metadata schema_migrations]
It seems like there should be a better way, but here is how I solved my problem:
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
This code assumes that you are following the standard model naming conventions for classes and source code files.
-
3It also assumes everything in your app/models/ is an active record model Apr 8, 2019 at 0:17
Don't know about active record, but here's a simple query:
select table_name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'