在 Rails 迁移中迁移数据
假设您有“lineitems”,并且您曾经根据 line_item 定义“make”。
最终您意识到 Make 可能应该位于其自己的模型上,因此您创建了一个 Make 模型。
然后,您想要从 line_items 表中删除 make 列,但对于每个带有 make 的 line_item,您想要 find_or_create_by(line_item.make)。
我如何在 Rails 迁移中有效地做到这一点?我很确定我可以为每个 line_item 运行一些简单的 find_or_create_by 但我担心后备支持,所以我只是在这里发布此内容以获取任何提示/建议/正确的方向。
谢谢!
Let's say you have "lineitems" and you used to define a "make" off of a line_item.
Eventually you realize that a make should probably be on its own model, so you create a Make model.
You then want to remove the make column off of the line_items table but for every line_item with a make you want to find_or_create_by(line_item.make).
How would I effectively do this in a rails migration? I'm pretty sure I can just run some simple find_or_create_by for each line_item but I'm worried about fallback support so I was just posting this here for any tips/advice/right direction.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想您应该在删除列之前检查 Make.count 是否等于 lineitems 中的唯一制造总数,如果不相等则引发错误。由于迁移是事务性的,如果它崩溃了,架构不会改变,迁移也不会被标记为已执行。因此,你可以这样做:
I guess you should check that the Make.count is equal to the total unique makes in lineitems before removing the column, and raise an error if it does not. As migrations are transactional, if it blows up, the schema isn't changed and the migration isn't marked as executed. Therefore, you could do something like this:
您可以在迁移中放入常规的 ruby 代码,这样您就可以创建新表,在旧模型上运行一些代码,将数据移动到新模型中,然后从原始模型中删除列。这甚至是可逆的,因此您的迁移仍然可以在两个方向上进行。
因此,根据您的情况,创建 Make 表并将
make_id
添加到 lineitem。然后,对于每个订单项,find_or_create
以及 lineitem 上的 make 列,将返回的 id 设置为 lineitem 上的新 make_id。完成后,从 lineitem 表中删除旧的 make 列。You can put regular ruby code in your migration, so you can create the new table, run some code across the old model moving the data into the new model, and then delete the columns from the original model. This is even reversible so your migration will still work in both directions.
So for your situation, create the Make table and add a
make_id
to the lineitem. Then for each line item,find_or_create
with the make column on lineitem, setting the returned id to the new make_id on lineitem. When you are done remove the old make column from the lineitem table.