sscirrus
sscirrus

Reputation: 56719

See all tables, all records from console?

How can I display the current record counts from all my database tables in one command using the console? Thanks!

Upvotes: 8

Views: 19196

Answers (4)

MZaragoza
MZaragoza

Reputation: 10111

I was trying to do this and I came up with my own way of doing this.

I like to encapsulate if into a model called Maintenance that is not a active record model

my model looks like

class Maintenance
  def self.show_all_tables_count
    list_table_with_count = []
    ActiveRecord::Base.connection.tables.each do |table|
      unless ['ar_internal_metadata', 'schema_migrations'].include?(table)
        list_table_with_count << [name: table, count: table.singularize.camelize.constantize.count]
      end
    end
    list_table_with_count
  end
end

I hope that this helps

Upvotes: 0

Sherwyn Goh
Sherwyn Goh

Reputation: 1352

ActiveRecord::Base.connection.tables

this will return an array of the tables you have, if you find it useful.

Upvotes: 16

Brian Deterling
Brian Deterling

Reputation: 13724

This will do it if you've 'touched' all your classes, but only for actual models:

ActiveRecord::Base.subclasses.map { |c| "#{c.name} => #{c.count}" }

If you really want all tables, including join tables that don't map to models:

ActiveRecord::Base.connection.tables.map { |t| "#{t} => " + ActiveRecord::Base.connection.execute("select count(*) from #{t}").fetch_row.first}

Upvotes: 17

Upgradingdave
Upgradingdave

Reputation: 13056

This might be a little longer than what you were hoping for, but hope this helps ;-)

Dir.glob('app/models/*.rb').each {|file| puts eval(File.basename(file, ".rb").classify + '.count').to_s + " #{File.basename(file, ".rb").classify.pluralize}"}

It might be better to create a rake task for this.

Upvotes: 1

Related Questions