DEV: Remove use of ActiveRecord in migration.

DEV: Remove use of ActiveRecord in migration.

It makes the migration brittle to changes. If I could I would go back in time and tell the 2016 version of me that.

diff --git a/db/migrate/20161202034856_add_uploads_to_categories.rb b/db/migrate/20161202034856_add_uploads_to_categories.rb
index b799e0c..7aa3b64 100644
--- a/db/migrate/20161202034856_add_uploads_to_categories.rb
+++ b/db/migrate/20161202034856_add_uploads_to_categories.rb
@@ -3,16 +3,20 @@ class AddUploadsToCategories < ActiveRecord::Migration[4.2]
     add_column :categories, :uploaded_logo_id, :integer, index: true
     add_column :categories, :uploaded_background_id, :integer, index: true
 
-    transaction do
-      Category.find_each do |category|
-        logo_upload = Upload.find_by(url: category.logo_url)
-        background_upload = Upload.find_by(url: category.background_url)
+    execute <<~SQL
+    UPDATE categories
+    SET uploaded_logo_id = u.id
+    FROM categories c
+    LEFT JOIN uploads u ON u.url = c.logo_url
+    WHERE u.url IS NOT NULL
+    SQL
 
-        category.update_columns(
-          uploaded_logo_id: logo_upload&.id,
-          uploaded_background_id: background_upload&.id
-        )
-      end
-    end
+    execute <<~SQL
+    UPDATE categories
+    SET uploaded_background_id = u.id
+    FROM categories c
+    LEFT JOIN uploads u ON u.url = c.background_url
+    WHERE u.url IS NOT NULL
+    SQL
   end
 end

GitHub sha: 7896c74c

1 Like

FIX: Incorrect DB query for `AddUploadsToCategories` migration.