環境
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