A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Friday, May 31, 2013

Listing all the models and numbers of records in a Rails application

Here is a rake task that will list all the ActiveRecord models in a Rails application along with the number of database records in each and the last time that database table was updated. Note the call to eager_load which ensure that all models are loaded.

This is a simple but very useful way to assess the contents of your database.

  desc "List model in application"
  task :list_models => :environment  do
    Rails.application.eager_load!

    ActiveRecord::Base.descendants.each do |model|
      name = model.name
      count = model.count
      last_date = count == 0 ? 'no data' : model.order('updated_at desc').first.updated_at
      printf "%-20s   %9d   %s\n", name, count, last_date
    end
  end

Archive of Tips