How to list of all the tables defined for the database when using active record?

Activerecord

Activerecord Problem Overview


How do I get a list of all the tables defined for the database when using active record?

Activerecord Solutions


Solution 1 - Activerecord

Solution 2 - Activerecord

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.

Solution 3 - Activerecord

> 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

Solution 4 - Activerecord

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.

Solution 5 - Activerecord

Don't know about active record, but here's a simple query:

select table_name from INFORMATION_SCHEMA.Tables where TABLE_TYPE = 'BASE TABLE'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJay StramelView Question on Stackoverflow
Solution 1 - ActiverecordFrançois BeausoleilView Answer on Stackoverflow
Solution 2 - ActiverecordThomas EView Answer on Stackoverflow
Solution 3 - ActiverecordHoracioView Answer on Stackoverflow
Solution 4 - ActiverecordJay StramelView Answer on Stackoverflow
Solution 5 - ActiverecordKonView Answer on Stackoverflow