Skip to content

Commit

Permalink
add migration
Browse files Browse the repository at this point in the history
  • Loading branch information
yksflip authored and mortbauer committed Mar 8, 2024
1 parent 71a8ded commit f161c04
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
4 changes: 2 additions & 2 deletions db/schema.rb
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema[7.0].define(version: 20240303231629) do
ActiveRecord::Schema[7.0].define(version: 2024_03_06_141647) do
create_table "action_text_rich_texts", charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.string "name", null: false
t.text "body", size: :long
Expand Down Expand Up @@ -135,7 +135,7 @@
t.datetime "created_at", precision: nil
t.datetime "updated_at", precision: nil
t.integer "parent_id"
t.boolean "folder"
t.boolean "folder", default: false, null: false
t.index ["parent_id"], name: "index_documents_on_parent_id"
end

Expand Down
@@ -0,0 +1,45 @@
class MoveDocumentsToActiveStorage < ActiveRecord::Migration[7.0]
def up
change_table :documents do |t|
t.boolean :folder, default: false, null: false
end

Document.find_each do |document|
if document.data.present? && document.mime.present?
document.attachment.attach(create_blob_from_document(document))
else
document.update(folder: true)
end
end

change_table :documents, bulk: true do |t|
t.remove :data
t.remove :mime
end
end

def down
change_table :documents, bulk: true do |t|
t.binary :data, limit: 16.megabyte
t.string :mime
t.remove :folder
end

Document.find_each do |document|
next unless document.attachment.attached?

document.update(
data: document.attachment.download,
mime: document.attachment.blob.content_type
)
end
end

def create_blob_from_document(document)
ActiveStorage::Blob.create_and_upload!(
io: StringIO.new(document.data),
filename: document.name,
content_type: document.mime
)
end
end

0 comments on commit f161c04

Please sign in to comment.