View all tables, all entries from the console?

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

+6
ruby-on-rails ruby-on-rails-3
source share
4 answers

This will be done if you β€œtouched” all your classes, but only for real models:

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

If you really need all the 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} 
+14
source share
 ActiveRecord::Base.connection.tables 

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

+16
source share

It may be a little longer than you hoped 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}"} 

Perhaps it would be better to create a rake task for this.

+1
source share

I tried to do this, and I came up with my own way to do it.

I like to encapsulate if in a model called Service , which is not an active write 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 this helps

0
source share

All Articles