UUID primary keys in Rails 3

Friday, June 10, 2011

Gemfile

# Gemfile
…
gem 'uuidtools'
…

migrations
# 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

model

# app/models/site.rb
class Site < ActiveRecord::Base
  include Extensions::UUID
end

extensions

# 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

This entry was tagged Rails, rails3 and SVN

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top