Using UUIDv7 with Ruby on Rails

There are some moving parts. First of all, even with built in support for UUID in PostgreSQL, since it is a function, the value won't be returned on insert. I think later Ruby on Rails versions solved this but I am not entirely sure about this.

The best way to handle this is to assign it in the model directly:

lang-ruby
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
  self.primary_key = "id"

  before_validation :generate_uuidv7, on: :create

  private

  def generate_uuidv7
    self.id = SecureRandom.uuid_v7
  end
end

Unfortunately, this isn't good enough. Even if we assign it, PostgreSQL would ignore that value and overwrite it with an assigned value. The trick is to create the table with the type UUID but without a default value (which would be the function to generate an uuid).

lang-ruby
class CreateThings < ActiveRecord::Migration[7.2]
  def change
    create_table :things, id: :uuid, default: nil do |t|
      t.string :name, null: false
    end
  end
end

That's it, now you have a table with sortable UUIDv7 for primary key.

Comments

No comments yet. Be the first to comment!
Your email address will be verified before your first comment is posted. It will not be displayed publicly.
Legal Information
By commenting, you agree to our Privacy Policy and Terms of Service.