Rails 5.1+ UUID as a primary key in ActiveRecord with PostgreSQL

Intro

For PostgreSQL >= 9.4, ActiveRecord will now use pgcrypto’s gen_random_uuid function whereas previously uuid-ossp’s uuid_generate_v4 function was used.

Follow these steps to add UUID primary keys to your Rails 5.1+ application.

Add a migration for pgcrypto

First we need to enable the PostgreSQL pgcrypto extension in a migration. Lets start by creating a blank migration:

$ rails generate migration enable_pgcrypto_extension

Then change the file to enable the extension. It should look something like this:

class EnablePgcryptoExtension < ActiveRecord::Migration[5.1]
  def change
    enable_extension 'pgcrypto'
  end
end

Change the primary default type

You can change the default id for newly generated migrations by adding the following to your config/application.rb file.

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

Posts example

Now if you run rails generate model post title:string your migration file should look something like this:

class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts, id: :uuid do |t|
      t.string :title

      t.timestamps
    end
  end
end