Skip to content

Instantly share code, notes, and snippets.

@jmkim
Created June 2, 2025 05:36
Show Gist options
  • Save jmkim/d47068fed1e0fe2d70c0fa9575d8d789 to your computer and use it in GitHub Desktop.
Save jmkim/d47068fed1e0fe2d70c0fa9575d8d789 to your computer and use it in GitHub Desktop.
Update all existing model IDs to UUIDv7 in a Ruby on Rails application
require 'uuid7'
def update_ids(model_class)
ActiveRecord::Base.transaction do
records = if model_class.column_names.include?('seq')
# Sort by the 'seq' column if the model has it, as it describes the sequence of the records
model_class.order(:seq)
elsif model_class.column_names.include?('created_at')
# Sort by the 'created_at' column, which is automatically generated by Ruby on Rails with 't.timestamps'
model_class.order(:created_at)
else
model_class.order(:id)
end
records.each do |record|
new_id = UUID7.generate
model_class.where(id: record.id).update_all(id: new_id)
end
end
end
Rails.application.eager_load!
models = ApplicationRecord.descendants
puts models.inspect # Show all models
models.each do |model|
if model.column_for_attribute(:id)&.type == :uuid
puts "Updating IDs for #{model.name}..."
update_ids(model)
else
puts "Skipping #{model.name} (id is not uuid)"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment