Ruby on Rails

How to use UUID in Rails | Benefits & Drawbacks

January 20, 2021

Author: Sajjad Umar

A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. Sometimes it is referred to as a 'globally unique identifier'.

Using UUID instead of a simple ID in your Rials application has the following benefits:

  • It is difficult to guess the number of records in your database
  • It is difficult to get data of some random user by just incrementing the id
  • It allows frontend developers to independently generate new objects without talking to the server

If you have decided to use the UUID in your Rails application beware of the following drawbacks:

  • As IDs are not incremental you can not fetch records with confidence using the following code (unless you set the default order to use the created_at column instead)
  • You can face some performance problems especially in databases like MySQL with a huge amount of data
  • It can also make debugging difficult i.e. it is fairly easy to work with a numeric ID instead of a random string
  • As UUID is 4-time larger than the 4-byte index value it will consume more memory in the database
  • The id can no longer be used for ordering the data

Enabling UUID in Ruby on Rails Application

As we have briefly discussed the benefits and drawbacks of using UUID lets jump into How we can set up our Rails application to use UUID instead of regular incremental IDs

To enable UUID in PostgreSQL we need to create a migration

rails g migration enable_uuid_support 

Add the following code in the generated migration file

# config/db/migrate/enable_uuid_support.rb
class EnableUuidSupport < ActiveRecord::Migration[6.0]
  def change
    enable_extension 'pgcrypto'

Now set UUID as the default primary key in the generators.rb file as follows

# config/initializers/generators.rb
Rails.application.config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid

Everything is set, now it’s time to create your first model using UUID. 

rails g model user name:string

And tell active record to use UUID as id with the following parameter id: :uuid

# config/db/migrate/create_user.rb
class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users, id: :uuid do |t|
      t.string :name


NOTE: You also need to set the type as UUID to every reference in your model see the below migration for the article model (article belongs to the user)

rails g model article

Generated migration’s code

# config/db/migrate/create_post_with_uuid.rb
class CreateArticle < ActiveRecord::Migration[6.0]
  def change
    create_table :users, id: :uuid do |t|
      t.string :title
      t.text :body

      # Note you have to manually specify the type now
      t.references :user, type: :uuid

That’s all! Happy coding!