Amir Sharif
Engineer.
Weekend hacker.
Self improvement enthusiast.

Using UUID for SQLite in Rails

Most tutorials online are on how to do this for Postgres. Here’s how to do it with SQLite and Rails 6+

Assume we’re creating a User model.

class CreateUsers < ActiveRecord::Migration[6.1]
  create_table :users, id: false do |t|
    t.string :id, null: false
  end
  add_index :users, :id, unique: true
end

You can use a string or blob type. As a general rule of thumb (YMMV) blob is slightly more performant and uses less disk space but is less easy to work with.

Now we need to make sure a UUID is assigned when you save the model.

class User < ApplicationRecord
  before_create :maybe_assign_id
  
  # ...
  
  def maybe_assign_id
    self.id = SecureRandom.uuid if self.id.blank?
  end
end

Take it for a spin:

2.7.4 :003 > User.create
   (0.7ms)  SELECT sqlite_version(*)
  TRANSACTION (0.1ms)  begin transaction
  User Create (0.5ms)  INSERT INTO "users" ("id", "created_at", "updated_at") VALUES (?, ?, ?)  [["id", "d48ccbbc-ff16-4815-acf5-30522bf4c30f"], ["created_at", "2022-09-16 17:13:26.189529"], ["updated_at", "2022-09-16 17:13:26.189529"]]
  TRANSACTION (1.1ms)  commit transaction
 => #<User id: "d48ccbbc-ff16-4815-acf5-30522bf4c30f", currency_amount: 0, currency_code: "USD", created_at: "2022-09-16 17:13:26.189529000 +0000", updated_at: "2022-09-16 17:13:26.189529000 +0000">

Other resources

  • You can use UUID v6 for time-based UUIDs. See gem uuid_v6.
  • If you want a solution in a gem you can use activeuuid.


Date
February 25, 2023