Last active
June 2, 2025 05:35
-
-
Save jmkim/97633dbff2f253b5d1c493ae1f4f22e8 to your computer and use it in GitHub Desktop.
Update all existing model IDs to UUIDv7 in a Ruby on Rails application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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