Skip to content

Commit 39d39b0

Browse files
committed
add migration
1 parent a1e0b08 commit 39d39b0

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

db/schema.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#
1111
# It's strongly recommended that you check this file into your version control system.
1212

13-
ActiveRecord::Schema[7.0].define(version: 20240303231629) do
13+
ActiveRecord::Schema[7.0].define(version: 2024_03_06_141647) do
1414
create_table "action_text_rich_texts", charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
1515
t.string "name", null: false
1616
t.text "body", size: :long
@@ -135,7 +135,7 @@
135135
t.datetime "created_at", precision: nil
136136
t.datetime "updated_at", precision: nil
137137
t.integer "parent_id"
138-
t.boolean "folder"
138+
t.boolean "folder", default: false, null: false
139139
t.index ["parent_id"], name: "index_documents_on_parent_id"
140140
end
141141

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class MoveDocumentsToActiveStorage < ActiveRecord::Migration[7.0]
2+
def up
3+
change_table :documents do |t|
4+
t.boolean :folder, default: false, null: false
5+
end
6+
7+
Document.find_each do |document|
8+
if document.data.present? && document.mime.present?
9+
document.attachment.attach(create_blob_from_document(document))
10+
else
11+
document.update(folder: true)
12+
end
13+
end
14+
15+
change_table :documents, bulk: true do |t|
16+
t.remove :data
17+
t.remove :mime
18+
end
19+
end
20+
21+
def down
22+
change_table :documents, bulk: true do |t|
23+
t.binary :data, limit: 16.megabyte
24+
t.string :mime
25+
t.remove :folder
26+
end
27+
28+
Document.find_each do |document|
29+
next unless document.attachment.attached?
30+
31+
document.update(
32+
data: document.attachment.download,
33+
mime: document.attachment.blob.content_type
34+
)
35+
end
36+
end
37+
38+
def create_blob_from_document(document)
39+
ActiveStorage::Blob.create_and_upload!(
40+
io: StringIO.new(document.data),
41+
filename: document.name,
42+
content_type: document.mime
43+
)
44+
end
45+
end

0 commit comments

Comments
 (0)