Eyal Levin
Eyal Levin

Reputation: 18454

Rails, Active Record - number of rows in tables

I got an email from Heroku saying I have too many rows in my Postgres DB.

How can I see how many rows I have in each table (so I can prioritize deletion)?

Upvotes: 0

Views: 1535

Answers (2)

Nuclearman
Nuclearman

Reputation: 5314

A better way to look at this might be:

How many records do I have for each of my AR models?

While it may not exactly match the numbers Heroku gives (may be a bit lower), and may have some extra stuff (that are not models), but for practical purposes, this is best option and it avoids the need to use SQL.

ActiveRecord::Base.descendants.map { |d| [d.all.size, d.name] }.sort

Explanation:

ActiveRecord::Base.descendants is a quick way to get all of the AR models. This is used to create an array of arrays that contains the [number of records, model name] to allow for simple lexicographic sorting. This should be enough to quickly determine where all your rows are going.

Upvotes: 2

toolz
toolz

Reputation: 891

heroku pg:psql (specify database name here if you have more than one)

Then check out this post to get a row count in postgres

How do you find the row count for all your tables in Postgres

Upvotes: 2

Related Questions