Rails 5 provides config to use UUID as primary key

Vijay Kumar Agrawal

Vijay Kumar Agrawal

April 4, 2016

This blog is part of our  Rails 5 series.

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


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

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.


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

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.

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

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.