我在迁移过程中编写了down
方法,以处理恢复将引用字段替换为字符串字段的迁移的问题。这是代码:
class ChangeCars < ActiveRecord::Migration[5.1]
def up
rename_column :cars, :make_id, :make_id_string
add_reference :cars, :make, foreign_key: true, optional: true
Cars.all.each do |car|
unless car.make_id_string.nil?
make = Make.find_by(uuid: car.uuid)
car.make_id = make
end
car.save!
end
remove_column :cars, :make_id_string
end
def down
add_column :cars, :make_id_string, :string
Cars.all.each do |car|
unless car.make.nil?
car.make_id_string = car.make.uuid
end
car.save!
end
# at this point :make_id_string -> String
remove_reference :cars, :make, index: true, foreign_key: true
rename_column :cars, :make_id_string, :make_id
# at this point :make_id -> Fixnum
end
end
似乎在删除引用时,我并没有完全清除它,因此当我替换make_id
字段时,它将采用该fixnum
类型。
任何建议都值得赞赏!
答案 0 :(得分:1)
如果make_id_string
中有真实数据,我强烈建议不要删除它。如果您在迁移过程中遇到一些错误,则可以节省您的时间。同样,恢复迁移将更加容易。
如果要迭代Car
中的所有模型,请不要使用#each
,因为如果将所有汽车都立即加载到内存中。使用https://www.w3schools.com/jquery/event_live.asp批量加载记录。