-
-
Save nowk/5183048 to your computer and use it in GitHub Desktop.
UUID as Primary Key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Gemfile | |
… | |
gem 'uuidtools' | |
… |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/site.rb | |
class Site < ActiveRecord::Base | |
include Extensions::UUID | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/extensions/uuid.rb | |
# | |
module Extensions | |
module UUID | |
extend ActiveSupport::Concern | |
included do | |
set_primary_key 'uuid' | |
before_create :generate_uuid | |
def generate_uuid | |
self.id = UUIDTools::UUID.random_create.to_s | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment