-
Often when diving into a new codebase or set of codebases the data model is the best way to get a sense for what's going on. But if it's been around for a while there'll be quite a few models that are no longer in use, models that use STI, and if it's part of a larger system, models that read/write to a different database with
establish_connection
. I like to be able put all models in a big spreadsheet where I can 1. Sort by updated_at to see which ones are no longer in use, and 2. Order by name and read down through them one by one. This snippet, run from a rails command line, helps me do that. -
Main Snippet
-
errors = [] models_and_databases = ActiveRecord::Base.descendants.map do |model| begin connection_spec = model.connection_pool.spec database_name = connection_spec.config[:database] || 'Unknown' table_name = model.table_name begin # Check if the model's table has an 'updated_at' column if model.column_names.include?('updated_at') # Fetch the latest updated_at value last_updated = model.order(updated_at: :desc).limit(1).pluck(:updated_at).first else last_updated = nil end rescue => e last_updated = nil end [model.name, { database: database_name, table: table_name, last_updated: last_updated }] rescue => e errors << "Error processing model: #{model.name}" errors << "Error message: #{e.message}" next end end.compact.to_h
-
Print out the hash
-
models_and_databases.each do |model_name, details| puts "#{model_name}, #{details[:table]}, #{details[:database]}, #{details[:last_updated]}" end;0
-
To add this to an airtable:
-
Copy paste it into a new text file
-
Do a find and replace for
,
- replace all occurences with the tab character. -
Copy and paste this into an airtable with the relevant 4 columns
-
-