Use Postgres UUID

Use UUIDs as the default primary key for your models
Icons/chart bar
Used 168 times
Created by
A Andrew Perkins

Usage
Once you've finished running this template, Rails will use UUID for any new models you create by default.

If adding foreign keys pointing at a UUID table, make sure to use type: :uuid

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments, id: :uuid do |t|
      t.references :post, null: false, type: :uuid, foreign_key: true
      t.timestamps
    end
  end
end

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/V4Ys1d"
Template Source

Review the code before running this template on your machine.

model_name = generate(:migration, 'enable_uuid')

command = <<-CODE
MIGRATION_FILE=$(find . -name "*enable_uuid.rb") && 
awk -v q=\\' '1;/change/{ print "    enable_extension" q "pgcrypto" q}' $MIGRATION_FILE > enable_uuid.rb &&
mv enable_uuid.rb $MIGRATION_FILE
CODE
inside('db/migrate') do
  run(command)
end


initializer 'generators.rb', <<-CODE
Rails.application.config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end
CODE
Comments
Julian Pinzon Eslava
Hey Andrew! I think it would be nice to add this extra bit to this template to enable default ordering by created at when using UUIDs
https://t.co/eEZpJqCbXX