squarefrog
squarefrog

Reputation: 4832

Rails migrate add column and populate with data from another column

If I change my mind about how I store Model data, how might I add new columns and migrate existing data over?

For example, would the following be appropriate:

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

Upvotes: 1

Views: 2867

Answers (1)

j-dexx
j-dexx

Reputation: 10416

Yes, but you should do Owner.reset_column_information first

I mean before updating the data.

Upvotes: 4

Related Questions