Skip to content

Instantly share code, notes, and snippets.

@oleoneto
Forked from wrburgess/1_initial_migration.rb
Created October 1, 2021 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oleoneto/50100655dba840525c91541b3e16f1ac to your computer and use it in GitHub Desktop.
Save oleoneto/50100655dba840525c91541b3e16f1ac to your computer and use it in GitHub Desktop.
Setting up UUID columns for Rails 5+ models utilizing Postgres 9.4+
class InitialMigration < ActiveRecord::Migration[5.0]
def change
enable_extension "pgcrypto" unless extension_enabled?("pgcrypto")
end
end
class ExampleMigration < ActiveRecord::Migration[5.0]
create_table :comments, id: :uuid, default: 'gen_random_uuid()' do |t|
# t.belongs_to :post, type: :uuid
t.references :post, type: :uuid
end
end

Notes

  • Default sorting in Rails is on the id column, which is no longer relevant when uuid types are used.
  • A default scope of default_scope -> { order("created_at ASC") } may be necessary for models.
  • Also a consideration is adding an index for the created_at column:
class AddCreatedAtIndexes < ActiveRecord::Migration
  def up
    add_index :categories, :created_at
    add_index :products, :created_at
    add_index :users, :created_at
  end
end

Refs

# This change should allow model generators to include instructions for uuid types by default
require_relative "boot"
...
module AppName
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.generators do |generator|
generator.orm :active_record, primary_key_type: :uuid
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment