Ruby on Rails

How to use UUID as a primary key in Rails 5.1+ and PostgreSQL

First of all, we need to enable PostgreSQL "pgcrypto" and "uuid-ossp" it’s called extension let’s try to generate a migration for these

$ rails g migration enable_pgcrypto_extension

now open this file from db/migrate/TIMESTAMPS_enable_pgcrypto_extension.rb and update like below

class EnablePgcryptoExtension < ActiveRecord::Migration[5.1]
  def change
     enable_extension 'uuid-ossp'
     enable_extension 'pgcrypto'

now complete the migration

$ rails db:migrate

now open application.rb and put these codes

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

    # Because I'm using :uuid for PK's, let me specify them as the default for FK's too.
    g.orm :active_record, foreign_key_type: :uuid

Great! You have done the technical steps.

Now need to create a table as like posts then the command looks like this

$ rails generate model Post title:string body:string

then open up this file and update like below

create_table :posts, id: :uuid do |t|
  t.string :title
  t.text :body

complete the migration after the edit.

Completely done the primary key as a UUID.

Fool Dev

I didn't get trained by the school system like other kids, and when I did concentrate on learning, my mind was cluttered and locked by the programming of the system. © Huey Newton