LoginSignup
0
0

More than 5 years have passed since last update.

[Ruby on Rails] マイグレーション中にモデルを使ってデータ移行をしたい

Posted at

Rails でカラムの構成や意味を変えたいときとかに、Modelを使って移行したくなりませんか?
そんなときのための、2つの怪しい方法を公開します。
(どのスキーマバージョンでも完全に動くものを作るのは不可能です。ちゃんと理解したうえで使ってくださいね)

インチキモデルクラスを作る

テーブルを旧テーブルから新テーブルに移行したいときとかに使えるやつです。

  • 旧モデルのテーブルをリネーム
  • モデルの旧コードをコピペ
  • 新モデルのテーブルを作成
  • コピーはモデルを使って行う

という発想です。
リレーションが複雑だったり、STIとかで、複数個のモデルを一つに統合する場合なんかに、使えます。

class CreteNewUsers < ActiveRecord::Migration[5.2]

  # 旧テーブル用のモデル
  class OldUser < ActiveRecord::Base
    self.table_name = 'old_users'
    # 修正前のモデルをコピペ
  end

  def change
     rename_table :users, :old_users
     create_table :users do |t|
        # 新しいフィールド
     end

     OldUser.all.each do |ou|
       User.create! name: ou.name, password: ou.password ...
     end

     # 自信があれば、コメントを外すw
     # remove_table :old_users
  end
end

スキーマをロードし直す

複数のモデルにまたがらないマイグレーションなら、スキーマをロードし直すのが手っ取り早いです。
ステータスの構成を変えたいとか、フィールドをカンマ区切りにしてたけど複数に分けたいとか、
そんな場合に使えます。

class ModifyUserTable < ActiveRecord::Migration[5.2]
  def change
    change_table :users do |t|
      # 変更
    end

    User.connection.schema_cache.clear!
    User.reset_column_information

    User.all.each do |u|
      u.status = User::INITIAL
    end
  end
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0