views:

37

answers:

1

I'm trying to work around Oracle's inability to change the type of a column with data in it. I cache the attribute's correct value, set it to nil, rename the column and then attempt to re-set the attribute:

class SwitchToForeignKeys < ActiveRecord::Migration
  def self.up
    registration_countries = {}
    Registration.all.each do |r|
      if c = Country.find_by_name(r.country)
        registration_countries[r.id] = c.id
        r.country = nil
        r.save
      end
    end

    rename_column :registrations, :country, :country_id
    change_column :registrations, :country_id, :integer

    Registration.reset_column_information
    registration_countries.each do |reg_id, country_id|
      r = Registration.find(reg_id)
      r.reload
      r.country_id = country_id
      r.save
    end
  end
end

On running the migration I get this error on the second r.save:

undefined method `country' for #<Registration:0x7f409698be48>
A: 

One workaround is to use execute:

registration_countries.each do |reg_id, country_id|
  execute "UPDATE registrations SET country_id = '#{country_id}' WHERE id = #{reg_id}"
end
execute "commit"
Steve