2010-09-03 66 views
0

我正在尝试解决Oracle无法更改其中包含数据的列的类型。我缓存属性的正确值,将其设置为无,重命名列,然后尝试重新设置属性:在Rails迁移中的rename_column后保存

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 

在运行迁移我上第二r.save此错误:

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

回答

0

一个解决办法是使用执行:

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