Ruby on rails Postgres提取多态性列
我有一个名为Ruby on rails Postgres提取多态性列,ruby-on-rails,postgresql,rails-migrations,Ruby On Rails,Postgresql,Rails Migrations,我有一个名为提要的下表: from_type | from_id -----------+--------- user | 1 project | 1 user | 2 program | 1 program | 2 project | 1 challenge | 1 project | 3 community | 1 我想把
提要的下表
:
from_type | from_id
-----------+---------
user | 1
project | 1
user | 2
program | 1
program | 2
project | 1
challenge | 1
project | 3
community | 1
我想把它转换成这样:
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
我这样做的原因是,如果我们需要回滚,就进行反向迁移。我用coalesce+update语句
成功地将底部版本转换为顶部版本,但我不太确定如何执行反向操作
这是向上迁移,向下迁移应该是什么样子
类多态FeedTable方法,则执行:
def up
%w[challenge community need program project user].each do |type|
execute("update feeds set from_id = #{type}_id where from_type = '#{type}'")
end
end
然后你可以看到回去的路,只要把作业倒过来:
def down
%w[challenge community need program project user].each do |type|
execute("update feeds set #{type}_id = from_id where from_type = '#{type}'")
# ------------------------^^^^^^^^^^^^^^^^^^^^
end
end
这假设您的表数据没有被破坏(即,您的from\u type
值与X\u id
列匹配)
您可以connection.quote(type)
而不是简单地手工将#{type}
用单引号括起来,但是您知道这些类型事先是安全的,因此不需要这样做。同样适用于连接。引用_column_name
和{type}\u id
插值。谢谢!我希望将它作为一条SQL语句来执行,但我认为这实际上是不必要的,只有几千条记录。而且可以安全地假设数据是干净的(我们在批准此迁移/重构之前验证了生产中的数据)。@KoriJohnRoys您可以使用动态SQL在一个查询中完成它(即SQL版本的eval
),但我认为不值得为可能永远不会使用的向下迁移而烦恼。我同意,对于向下迁移,我希望永远不会使用它。