Skip to content

Instantly share code, notes, and snippets.

@ntamvl
Created May 11, 2016 06:39
Show Gist options
  • Save ntamvl/4bf181342dc14fe3e1d15f7dd4517915 to your computer and use it in GitHub Desktop.
Save ntamvl/4bf181342dc14fe3e1d15f7dd4517915 to your computer and use it in GitHub Desktop.
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:

class EnableUuidExtension < ActiveRecord::Migration
  def change
    enable_extension 'uuid-ossp'
  end
end

Next, create a model

rails g model Book title

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

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:

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!

source: http://blog.mccartie.com/2015/10/20/default-uuid's-in-rails.html

@johansenja
Copy link

🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment