0
0

More than 1 year has passed since last update.

【Rails】マイグレーション時に既存データも一緒に更新する方法

Posted at

環境

Rails 6.0.1
Ruby 2.6.3
PostgreSQL 11.16

前提

Categoryモデルにcodeというカラムがあったがnameを追加したい
その際、下記の既存データのcodeの値をnameカラムに更新したい

Category.seed(:id,
  { id: 1, code: Category.code.ruby.value },
  { id: 2, code: Category.code.rails.value },
  { id: 3, code: Category.code.php.value },
  { id: 4, code: Category.code.laravel.value },
  { id: 5, code: Category.code.js.value },
  { id: 6, code: Category.code.java.value },
  { id: 7, code: Category.code.kotlin.value },
  { id: 8, code: Category.code.sql.value },
)

migrationファイルの書き方

nameカラムを追加する際に既存データの値を更新する処理を一緒に書く。

class AddNameColumnToCategory < ActiveRecord::Migration[6.0]
    def up
      add_column :categories, :name, :string, null: false, default: false
    
      Category.all.each do |category|
        category.update!(name: category.code)
      end
    end
    
    def down
      remove_column :categories, :name, :string
    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