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

2

8

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 :(

Audiometer answered 8/2, 2017 at 18:46 Comment(0)
L
17

This should work:

  ActiveRecord::Base.connection.tables.map { |t| {t=>  ActiveRecord::Base.connection.execute("select count(*) from #{t}")[0]} }
Leeuwenhoek answered 8/2, 2017 at 18:58 Comment(0)
J
1
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
}
Jylland answered 29/11, 2022 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.