如何在Rails迁移中将一列(包含内容)移动到另一个表? [英] How do I move a column (with contents) to another table in a Rails migration?

查看:67
本文介绍了如何在Rails迁移中将一列(包含内容)移动到另一个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些列从一个现有表移动到另一个表。

I need to move some columns from one existing table to another. How do I do it using a rails migration?

class AddPropertyToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :someprop, :string
    remove_column :profiles, :someprop
  end

  def self.down
    add_column :profiles, :someprop, :string
    remove_column :users, :someprop
  end
end

上面只是创建新列,但值保留为空...

The above just creates the new columns, but values are left empty...

我要避免记录

如果可以通过编程方式移动列值,性能特征是什么?它会逐行执行,还是可以批量更新?

If there is a way to move column values programmatically, what are the performance characteristics? Would it do row-by-row, or is there a way to update in bulk?

推荐答案

我最终使用了这种迁移(经过测试,它可以正常工作,并成功回滚):

I ended up using this migration (tested, it works, and rolls back successfully):

class AddPropertyToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :someprop, :string
    execute "UPDATE users u, profiles p SET u.someprop = p.someprop WHERE u.id = p.user_id"
    remove_column :profiles, :someprop
  end

  def self.down
    add_column :profiles, :someprop, :string
    execute "UPDATE profiles p, users u SET p.someprop = u.someprop WHERE p.user_id = u.id"
    remove_column :users, :someprop
  end
end

我喜欢它,因为它避免了大型数据库上的逐行更新。

I like it because it avoids the row-by-row updates on a large database.

这篇关于如何在Rails迁移中将一列(包含内容)移动到另一个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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