Skip to content

Instantly share code, notes, and snippets.

@wrburgess
Last active December 7, 2023 14:14
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save wrburgess/c1678788181d5f5577c6e84ac5a3efab to your computer and use it in GitHub Desktop.
Save wrburgess/c1678788181d5f5577c6e84ac5a3efab 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
@philip13
Copy link

philip13 commented Apr 6, 2022

Hi everyone, please help me with this question, what happen if we already have data on our database, how can I convert all classic IDs to uuids? Is it converting automatically ?

@wrburgess
Copy link
Author

@philip13 I don't believe there is any automatic way to achieve your goal. You need to change the ids from integers to uuids on both main tables and any foreign keys across multiple.

@philip13
Copy link

@wrburgess thank you, let me try and test, and tell you!  :)

@ViniKohler
Copy link

Hello everyone! Please help me with this... I want to use UUID as a columnf rom a table, but I don`t want to use it as a primary key. How can I do it?

@wrburgess
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment