0

i need to convert some data, but not sure how to do it.

I have a professional model, which had an foreign key. We decided that wasn't enough and changed the "has many" to a HABTM model, but now in the production environment, i need to convert the data from the foo_id field to the professional_foo joint table.

The "add table" migration will be executed before the "drop column" one, but how should i set up a conversion knowing that i have databases in use that use the old form and i will have new setups of the system that will be made straight to the last code version and because that, wont need any conversion to be done. (initializes scripts on newest version are already fixed.

Techmago
  • 380
  • 4
  • 18

1 Answers1

0

I recommend doing the conversion of data in the migration between the add table and the drop column. This migration should be run when the new code is deployed so the new code will work with the new data structure and new installations that don't have any data yet will just run the migration very fast since there won't be data to convert.

The migration would look something like:

class OldProfessional < ActiveRecord::Base
  self.table_name = "professionals"
  has_many :foos
end
class NewProfessional < ActiveRecord::Base
  self.table_name = "professionals"
  has_and_belongs_to_many :foos
end

class MigrateFoosToHasAndBelongsToMany < ActiveRecord::Migration
  def up
    OldProfessional.all.each do |old_pro|
      new_pro = NewProfessinoal.find(old_pro.id)
      old_pro.foos.each do |foo|
        new_pro.foos << foo
      end
      new_pro.save!
    end
  end
  def down
    NewProfessional.all.each do |new_pro|
      old_pro = OldProfessional.find(new_pro.id)
      new_pro.foos.each do |foo|
         old_pro.foos << foo
      end
      old_pro.save!
    end
  end
end
Coenwulf
  • 1,937
  • 2
  • 15
  • 23