active_sanity: Spot invalid records in your database

ActiveRecord is great way to ensure your models are valid before saving them to the database. But as you add new validations or update existing ones, some of the existing records could become invalid. Do you have any invalid records in your production database?

It’s too late when you discover there are invalid records in your production environment.

  • Maybe a migration failed half way through when you deploy to production “It was working just fine on staging?!”
  • You get notified about a weird bug (and you can’t reproduce it on your dev machine)
  • Someone sends you an email saying that he can’t buy the dancing banana t-shirt on your webstore (and you’re lucky someone contacted you. How many people went to a concurrent webstore?)

Setup active_sanity, run it and fix your records.

  1. Add the following line to your Gemfile:

      gem "active_sanity"
  2. Run rake db:check_sanity on your production database. You should see something like:

    model       | id  | errors
    User        |   1 | { "email" => ["is invalid"] }
    Flight      | 123 | { "arrival_time" => ["can't be nil"], "departure_time" => ["is invalid"] }
    Flight      | 323 | { "arrival_time" => ["can't be nil"]
  3. Want to store those “invalid records” in the database to check them in your admin interface? Just run rails generate active_sanity to generate a migration and access the data through a model called InvalidRecord.

Run active_sanity against your production environment, say “OMG!” and go fix your records. Deployments will be less stressful and you’re gonna sleep better at night.