🎉 I added a new feature to Rails: Default to `uuid` as primary key when generating database migrations. Enjoy! https://t.co/u0UNmJk98O
— Jon McCartie (@jmccartie) October 20, 2015
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:
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
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.
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:
Now, whenever you generate a migration, we’ll tag on id: :uuid
to the create_table
method.
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!
Writer. Musician. Adventurer. Nerd.
Purveyor of GIFs and dad jokes.