Jose Perez
Jose Perez

Reputation: 106

Rails 5 How to get a count of all the rows in each table

I had a old script that worked for me on rails 4

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

but this is not returning anything on a rails 5 project :(

Upvotes: 8

Views: 2969

Answers (2)

spirito_libero
spirito_libero

Reputation: 1332

ActiveRecord::Base.connection.tables.inject({}) { |h,t| h[t] =  ActiveRecord::Base.connection.execute("select count(*) from #{t}")[0].values.first; h }

will produce nice output like:

{
  "users" => 12,
  "teams" => 5
}

Upvotes: 1

Joel Blum
Joel Blum

Reputation: 7888

This should work:

  ActiveRecord::Base.connection.tables.map { |t| {t=>  ActiveRecord::Base.connection.execute("select count(*) from #{t}")[0]} }

Upvotes: 17

Related Questions