Skip to content

Instantly share code, notes, and snippets.

@rmoriz
Last active February 7, 2020 12:30
Show Gist options
  • Star 54 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save rmoriz/937739 to your computer and use it in GitHub Desktop.
Save rmoriz/937739 to your computer and use it in GitHub Desktop.
UUID primary keys in Rails 3
# Gemfile
gem 'uuidtools'
# db/migrate/20110422210841_create_sites.rb
# 1. :id => false
# 2. :uuid
#
class CreateSites < ActiveRecord::Migration
def self.up
create_table(:sites, :id => false) do |t|
t.string :uuid, :limit => 36, :primary => true
t.timestamps
end
end
def self.down
drop_table :sites
end
end
# app/models/site.rb
class Site < ActiveRecord::Base
include Extensions::UUID
end
# app/models/extensions/uuid.rb
#
module Extensions
module UUID
extend ActiveSupport::Concern
included do
# old rails versions
set_primary_key 'uuid'
# later rails versions, untested:
# self.primary_key = 'the_name'
before_create :generate_uuid
def generate_uuid
self.id = UUIDTools::UUID.random_create.to_s
end
end
end
end
@natebird
Copy link

If you are using Ruby 1.9.3+ you can just call SecureRandom.uuid. You also don't need gem 'uuidtools'.

Thanks for this.

@SandNerd
Copy link

For Rails 3.1+ check ActiveUUID

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