perpetuum mobile
21. 08. 2014. database * ruby

Adding UUID to rails

In concern

module Uuid
  extend ActiveSupport::Concern

  included do
    before_create :generate_uuid
  end

  protected

  def generate_uuid
    self.uuid = loop do
      random_uuid = SecureRandom.urlsafe_base64(nil, false)
      break random_uuid unless self.class.exists?(uuid: random_uuid)
    end
  end
end

Resources