DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

Data transfer with Migration (マイグレーション中のデータ移行)

Point

Model.reset_column_information
Enter fullscreen mode Exit fullscreen mode

It makes AR reload the column information.

Example

class ChangeColumnTypeInCompanies < ActiveRecord::Migration[6.0]
  def up
    add_column    :companies, :r_id, :string, comment: 'registration_id', after: :id

    # マイグレーション中にデータ移行するので、直前に足したカラム情報を読み込む
    # https://github.com/rails/rails/blob/v5.1.4/activerecord/lib/active_record/migration.rb#L409-L424
    Company.reset_column_information
    Company.find_each {|company|
      company.update(r_id: company.registration_number&.to_s)
    }
    remove_column :companies, :registration_number
  end

  def down
    add_column    :companies, :registration_number, :integer
    Company.reset_column_information
    Company.find_each {|company|
      company.update(registration_number: company.r_id&.to_s)
    }
    remove_column :companies, :r_id

  end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
mikerogers0 profile image
Mike Rogers ✈️ • Edited

I've been trying to avoid reset_column_information in favour of execute where I can. Mostly because it's faster, but also because it'll work if the Company model ever changes in the future.