我正在尝试解决Oracle无法更改包含数据的列类型的问题。我缓存属性的正确值,将其设置为nil,重命名列,然后尝试重新设置属性:
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 :(得分:0)
一种解决方法是使用execute:
registration_countries.each do |reg_id, country_id|
execute "UPDATE registrations SET country_id = '#{country_id}' WHERE id = #{reg_id}"
end
execute "commit"