Forked from kylefox/001_add_record_uuid_to_active_storage_attachments.rb
Created
September 9, 2021 03:53
-
-
Save ismarsantos/fa00ae17ee068fe329243f7300515364 to your computer and use it in GitHub Desktop.
Migrations that make ActiveStorage attachments work with UUID primary keys. https://github.com/rails/rails/pull/32466
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
class AddRecordUuidToActiveStorageAttachments < ActiveRecord::Migration[5.2] | |
def change | |
# After applying this migration, you'll need to manually go through your | |
# attachments and populate the new `record_uuid` column. | |
# If you're unable to do this, you'll probably have to delete all your attachments. | |
# You've pretty much got useless garbage data if that's the case :( | |
add_column :active_storage_attachments, :record_uuid, :uuid | |
end | |
end |
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
class ChangeActiveStorageAttachmentsRecordIdToUuid < ActiveRecord::Migration[5.2] | |
def up | |
remove_record_id_index! | |
# Rename the built-in record_id:int column and allow NULL values. | |
rename_column :active_storage_attachments, :record_id, :record_id_int | |
change_column_null :active_storage_attachments, :record_id_int, true | |
# Rename our (now populated) UUID column to `record_id` and prevent NULL values. | |
rename_column :active_storage_attachments, :record_uuid, :record_id | |
change_column_null :active_storage_attachments, :record_id, false | |
add_record_id_index! | |
end | |
def down | |
remove_record_id_index! | |
# Rename our UUID column back to `record_uuid` and once again allow NULL values. | |
rename_column :active_storage_attachments, :record_id, :record_uuid | |
change_column_null :active_storage_attachments, :record_uuid, true | |
# Rename `record_id_int` back to record_id:int column and prevent NULL values. | |
rename_column :active_storage_attachments, :record_id_int, :record_id | |
change_column_null :active_storage_attachments, :record_id, false | |
add_record_id_index! | |
end | |
private | |
def add_record_id_index! | |
add_index :active_storage_attachments, [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true | |
end | |
def remove_record_id_index! | |
remove_index :active_storage_attachments, column: [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment