tags:

views:

775

answers:

3

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

A: 

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

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

Kon
A: 

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.

Jay Stramel
+6  A: 

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:

François Beausoleil