UUID as Primary Key in Mysql

Last post was about how we can use uuid as primary key in postgres database. In this post going further, uuid is implemented in mysql qit rails.

  • Change the migration file as :
  • 20140517074955_create_users.rb
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    class CreateUsers < ActiveRecord::Migration
      def self.up
        create_table(:users, :id => false) do |t|
          t.string :uuid, :limit => 36, :primary => true
          t.string :name
          t.string :email
          t.string :password_digest
          t.timestamps
        end
      end
    
      def self.down
        drop_table :users
      end
    
    end
    

  • Create a module uuid.rb
  • uuid.rb
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    module Extensions
      module UUID
        extend ActiveSupport::Concern
    
        included do
          # old rails versions
          # set_primary_key 'uuid'
          self.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
    

  • Include module into your Model
  • User.rb
    1
    2
    3
    4
    5
    6
    
    class User < ActiveRecord::Base
    
      #———————– External Dependencies ——————–#
      include Extensions::UUID
    
    end
    

    That is it. Rest everything is same as default. Now instead of id, uuid is created and saved for every model where we include our module.

Comments