Rails named_column更改列的类型

时间:2019-08-29 15:14:09

标签: ruby-on-rails ruby postgresql

我在迁移过程中编写了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类型。

任何建议都值得赞赏!

1 个答案:

答案 0 :(得分:1)

  1. 如果make_id_string中有真实数据,我强烈建议不要删除它。如果您在迁移过程中遇到一些错误,则可以节省您的时间。同样,恢复迁移将更加容易。

  2. 如果要迭代Car中的所有模型,请不要使用#each,因为如果将所有汽车都立即加载到内存中。使用https://www.w3schools.com/jquery/event_live.asp批量加载记录。