I have the following table called feeds:
from_type | from_id
-----------+---------
user | 1
project | 1
user | 2
program | 1
program | 2
project | 1
challenge | 1
project | 3
community | 1
and I'd like to transform it to this:
from_type | user_id | project_id | program_id | challenge_id | community_id
-----------+---------+------------+------------+--------------+-------------
user | 1 | | | |
project | | 1 | | |
user | 2 | | | |
program | | | 1 | |
program | | | 2 | |
project | | 1 | | |
challenge | | | | 1 |
project | | 3 | | |
community | | | | | 1
My reason for doing so is to have the reverse migration if we need to roll back. I managed to transform the bottom version to the top version with a coalesce + update statement, but I'm less sure how to perform the reverse operation.
Here's the up migration, what should the down migration look like?
class PolymorphicFeedTable < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
UPDATE feeds SET
from_id = coalesce(user_id, project_id, community_id, challenge_id, program_id, need_id);
SQL
end
def down
execute <<-SQL
?
SQL
end
end