# Migration Timestamps deleted_at Magic Field

> Extending Rails migration timestamps to automatically include a deleted_at column for acts_as_paranoid

- Author: Curtis Miller
- Published: 2007-07-04
- Categories: rails, how-to
- Canonical URL: https://millarian.com/posts/migration-timestamps-with-deleted_at-magic-field/

I was recently working on a project using edge rails and saw that it supported something like what used to be called [sexy migrations](http://errtheblog.com/post/2381). Basically, you can make your migration files look a whole lot cleaner.

## Before

```ruby
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column :first_name, string
      t.column :last_name, string
      t.column :birthday, date
      t.column :created_at, datetime
      t.column :updated_at, datetime
    end
  end

  def self.down
    drop_table :users
  end
end
```

## After

```ruby
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :first_name, :last_name
      t.date :birthday
      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end
```

Looks much better doesn't it? For what I was doing though, I wanted to use the acts\_as\_paranoid (dead link: http://ar-paranoid.rubyforge.org/) functionality to never delete anything. The acts\_as\_paranoid plugin updates the row with a deleted\_at timestamp and then filters out 'deleted' ones whenever it queries the database. Of course, I could just add `t.datetime :deleted_at` to each table. But instead of going back to the old way of doing things, I simply extended the built in timestamps functionality by placing the following in a file in the lib directory and then requiring it in the environment.

## lib/custom\_schema\_definitions.rb

```ruby
module ActiveRecord
  module ConnectionAdapters #:nodoc:
    class TableDefinition

      # Adds a deleted_at column when timestamps is called from a migration.
      def timestamps_with_deleted_at
        timestamps_without_deleted_at
        column(:deleted_at, :datetime)
      end

      alias_method_chain :timestamps, :deleted_at
    end
  end
end
```

## config/environment.rb (add)

```ruby
require "custom_schema_definitions"
```

Now, we can run our migration as we did before and the `t.timestamps` line will also give us a `deleted_at` column. Share your paranoid ramblings in the comments.

_Note: I believe this only works in [Edge Rails](http://wiki.rubyonrails.org/rails/pages/EdgeRails) for the moment as the new migrations and alias\_method\_chain are not present in the latest stable version of Rails._
