Rails迁移添加列并填充来自另一列的数据

时间:2014-03-13 10:23:03

标签: ruby-on-rails rails-migrations

如果我改变主意关于如何存储模型数据,我该如何添加新列并迁移现有数据?

例如,以下是适当的:

class AddPropertyAAndPropertyBToOwner < ActiveRecord::Migration
  def change
    add_column :owners, :property_a, :string
    add_column :owners, :property_b, :string

    # Now I need to migrate the existing 40 records
    # populating the new columns from an existing one
    # Owner.all.each do |o|
    #   original = o.original_property
    #   o.property_a = original.match(/foo/).captures.first
    #   o.proptery_b = original.match(/bar/).captures.first
    #   o.save
    # end
  end
end

1 个答案:

答案 0 :(得分:3)

是的,但你应该先Owner.reset_column_information

我的意思是在更新数据之前。