在Rails迁移中迁移数据 [英] Migrating Data in a Rails Migration

查看:80
本文介绍了在Rails迁移中迁移数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,您有"lineitems",并且您曾经根据line_item定义了"make".

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.

然后,您想从line_items表中删除make列,但是对于每个要生成的make的line_item,您都想find_or_create_by(line_item.make).

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).

在Rails迁移中,我将如何有效地做到这一点?我很确定我可以为每个line_item运行一些简单的find_or_create_by,但是我担心后备支持,所以我只是在此处发布此技巧/建议/正确的方向.

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.

谢谢!

推荐答案

我想您应该在删除列之前检查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:

class CreateMakesAndMigrateFromLineItems < ActiveRecord::Migration
  def self.up
    create_table :makes do |t|
      t.string :name
      …
      t.timestamps
    end

    makes = LineItem.all.collect(:&make).uniq
    makes.each { |make| Make.find_or_create_by_name make }
    Make.count == makes.length ? remove_column(:line_items, :make) : raise "Boom!"

  end

  def self.down
    # You'll want to put logic here to take you back to how things were before. Just in case!
    drop_table :makes
    add_column :line_items, :make
  end
end

这篇关于在Rails迁移中迁移数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆