迁移数据-不仅仅是模式,Rails [英] Migrating DATA - not just schema, Rails

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

问题描述

有时候,需要迁移数据。随着时间的流逝,使用域模型进行的代码更改和迁移将不再有效,迁移将失败。迁移数据的最佳做法是什么?

Sometimes, data migrations are required. As time passes, code changes and migrations using your domain model are no longer valid and migrations fail. What are the best practices for migrating data?

我尝试举一个例子来阐明问题:

I tried make an example to clarify the problem:

考虑这个。您有迁移

class ChangeFromPartnerAppliedToAppliedAt < ActiveRecord::Migration
  def up
    User.all.each do |user|
      user.applied_at = user.partner_application_at
      user.save
   end
 end

这当然很好。稍后,您需要更改架构

this runs perfectly fine, of course. Later, you need a schema change

class AddAcceptanceConfirmedAt < ActiveRecord::Migration
  def change
    add_column :users, :acceptance_confirmed_at, :datetime
  end
end

class User < ActiveRecord::Base
  before_save :do_something_with_acceptance_confirmed_at
end

对您来说,没有问题。它运行完美。但是,如果您的同事今天同时提起这两个操作,还没有运行第一次迁移,他将在运行第一次迁移时出现此错误:

For you, no problem. It runs perfectly. But if your coworker pulls both these today, not having run the first migration yet, he'll get this error on running the first migration:

rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `acceptance_confirmed_at=' for #<User:0x007f85902346d8>

那不是团队合作者,他将解决您引入的错误。您应该做什么?

That's not being a team player, he'll be fixing the bug you introduced. What should you have done?

推荐答案

最佳实践是:在迁移中不要使用模型。迁移会更改AR映射的方式,因此完全不要使用它们。使用SQL完成所有操作。这样,它将始终有效。

Best practice is: don't use models in migrations. Migrations change the way AR maps, so do not use them at all. Do it all with SQL. This way it will always work.

此:

User.all.each do |user|
  user.applied_at = user.partner_application_at
  user.save
end

我会这样

update "UPDATE users SET applied_at=partner_application_at"

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

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