Skip to content

Instantly share code, notes, and snippets.

@matiaskorhonen
Last active December 15, 2018 21:40
Show Gist options
  • Save matiaskorhonen/eef09ddc9114df8e88caa8d85f5da5e2 to your computer and use it in GitHub Desktop.
Save matiaskorhonen/eef09ddc9114df8e88caa8d85f5da5e2 to your computer and use it in GitHub Desktop.
UUID Rails tips
# config/initializers/active_record_uuid_ids.rb
Rails.application.config.generators do |generator|
# Always use UUIDs for primary keys (when generating migrations)
generator.orm :active_record, primary_key_type: :uuid
end
class EnableUuidOssp < ActiveRecord::Migration[5.0]
def change
# Enable the UUID extension in PostgreSQL
enable_extension "uuid-ossp"
end
end
class CreateUsers < ActiveRecord::Migration[5.0]
def change
# "id: :uuid" should be generated automatically when
# generating new migrations (with the above initializer)
create_table :users, id: :uuid do |t|
t.string :name
t.string :email
t.timestamps
end
add_index :users, :email
end
end
class CreateIdentities < ActiveRecord::Migration[5.0]
def change
create_table :identities do |t|
t.references :user, foreign_key: true, type: :uuid # Remember to specify the foreign key type!
t.string :uid
t.string :provider
t.timestamps
end
end
end

Miscellaneous tips

  • #find_each doesn't really work with UUIDs (the record IDs aren't guarenteed to be in any specific order)
  • Remember to order collections in index views (there's no deterministic order by default)
  • Nesting resources is extra bad with UUID IDs since they're so long. Avoid deep nesting!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment