Default UUID's In Rails

UUID’s

I love UUID’s. You should use them. Rails 4 makes it simple to get setup and use UUID’s throughout your project.

First, we enable UUID’s:

rails g migration enable_uuid_extension

This creates the following migration:

1
2
3
4
5
class EnableUuidExtension < ActiveRecord::Migration
  def change
    enable_extension 'pgcrypto'
  end
end

Next, create a model

rails g model Book title

The Problem

Unfortunately, this creates an integer-based primary key migration:

1
2
3
4
5
6
7
8
class CreateBooks < ActiveRecord::Migration
  def change
    create_table :books do |t|
      t.string :title
      t.timestamps
    end
  end
end

To move forward, you must fiddle with that migration to add id: :uuid to the create_table method:

1
2
3
4
5
6
7
8
class CreateBooks < ActiveRecord::Migration
  def change
    create_table :books, id: :uuid do |t|
      t.string :title
      t.timestamps
    end
  end
end

After spending a few weeks on a new project doing this, I figured we could make a change to Rails to allow this to happen. Here’s how.

The Solution

I recently had a change merged into Rails you should know about. Here’s a look at the original commit, then a follow-up to make a few minor modifications.

In application.rb, simply make the following addition:

config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

Now, whenever you generate a migration, we’ll tag on id: :uuid to the create_table method.

Warning

You must have already added a UUID extension to your database. If not, running this migration will fail. So don’t forget the rails g migration enable_uuid_extension migration up front.

Enjoy!

Hi there, I'm Jon.

Writer. Musician. Adventurer. Nerd.

Purveyor of GIFs and dad jokes.