Skip to content

Instantly share code, notes, and snippets.

@chsh
Forked from rmoriz/Gemfile
Last active December 16, 2015 23:59
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 chsh/5517937 to your computer and use it in GitHub Desktop.
Save chsh/5517937 to your computer and use it in GitHub Desktop.
1. Use SecureRandom.uuid instead of UUIDTools. 2. Belonging models should specify string type refering Site. 3. Apply Ruby 1.9 or higher syntax. ;-)
# 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: 32, primary: true
t.timestamps
end
end
def self.down
drop_table :sites
end
end
class CreateLinks < ActiveRecord::Migration
def self.up
create_table :links do |t|
t.string :site_id, limit: 32
t.timestamps
end
add_index :links, :site_id
end
def self.down
drop_table :sites
end
end
# app/models/site.rb
class Site < ActiveRecord::Base
include Extensions::UUID
has_many :links
end
# app/models/extensions/uuid.rb
#
module Extensions
module UUID
extend ActiveSupport::Concern
included do
self.primary_key = 'uuid'
before_create :generate_uuid
def generate_uuid
self.id = SecureRandom.uuid.gsub(/-/, '')
end
end
end
end
@kingpong
Copy link

Are you sure primary: true is working? When I run your migration, the uuid column is nullable and the table has no primary key. I'm running Rails 3.2.13, and this happens with both mysql and sqlite. This is the generated table:

CREATE TABLE `sites` (
  `uuid` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

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