DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay