Rails 5 provides config to use UUID as primary key

Vijay Kumar Agrawal

By Vijay Kumar Agrawal

on April 4, 2016

This blog is part of our  Rails 5 series.

UUIDs are a popular alternative to auto-incremental integer primary keys.

2create_table :users, id: :uuid do |t|
3  t.string :name

Notice that id: :uuid is passed to create_table. This is all we need to do to have UUID as primary key for users.

Now, if an application is designed to use UUID instead of Integer, then chances are that new tables too would use UUID as primary key. And it can easily get repetitive to add id: :uuid in create_table , every time a new model is generated.

Rails 5 comes up with a solution. We need to set primary key as UUID in config/application.rb.

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

This automatically adds id: :uuid to create_table in all future migrations.

If we are using the latest version of PostgreSQL then we should enable pgcrypto extension as per Rails guide.

To enable pgcrypto extension we need a migration which does something like this.

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

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.