Rails Migration

example code - 単独のマイグレーション

crate table

rails generate migration CreateProducts name:string part_number:string
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :part_number
    end
  end
endp

add column

rails generate migration AddPartNumberToProducts part_number:string
class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
  end
end

add index

rails generate migration AddPartNumberToProducts part_number:string:index
class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
    add_index :products, :part_number
  end
end

migration file syntax

dataタイプが違う場合にchange_column

postgresqlでしかテストしてない。

integer to boolean

sqliteを使っていたが、booleanに変更したかった。

change_column :message_parts, :is_attachment, 'bool USING CASE WHEN is_attachment=0 THEN FALSE ELSE TRUE END;'

string to integer

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

zero downtime migration

Zero Downtime Migrations with ActiveRecord and PostgreSQL

References

migration commands

zero downtime

results matching ""

    No results matching ""