目的
Ectoで再マイグレーションを実施する。
実行環境
OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4
Phoenix Framework: v0.13.1
PostgreSQL: postgres (PostgreSQL) 9.4.4
始める前に
私が行ったプロジェクト作成を書いておきます。
>cd プロジェクト作成ディレクトリ
>mix phoenix.new ecto_models_sample
>cd ecto_models_sample
>mix phoenix.server
>ctrl+c
>mix phoenix.gen.html User users name:string email:string
ルーティングの追加
>mix ecto.create
>mix ecto.migrate
準備良し。
以降、この記事でのプロジェクトと言えば、
ecto_models_sample
を指し示す。
マイグレーションして生成したテーブルにカラムの追加/削除を行います。
今回は、usersテーブルに対してageの項目を追加/削除してみる。
目次
- カラム追加
- カラム削除
- まとめ
1. カラム追加
ectoのコマンドを使ってマイグレーションファイルを生成します。
名称は、処理_カラム名_to_テーブル名
とすると分かりやすいのではないでしょうか。
>mix ecto.gen.migration add_age_to_users
* creating priv/repo/migrations
* creating priv/repo/migrations/20150630005902_add_age_to_users.exs
priv/repo/migrations/20150630005902_add_age_to_users.exsを
以下のように編集しました。
defmodule EctoModelsSample.Repo.Migrations.AddAgeToUsers do
use Ecto.Migration
def change do
alter table(:users) do
add :age, :integer
end
end
end
マイグレーションしてカラムを追加します。
>mix ecto.migrate
[info] == Running EctoModelsSample.Repo.Migrations.AddAgeToUsers.change/0 forward
[info] alter table users
[info] == Migrated in 0.0s
2. カラム削除
カラムを削除します。
>mix ecto.gen.migration remove_age_to_users
* creating priv/repo/migrations
* creating priv/repo/migrations/20150630014132_remove_age_to_users.exs
作成されたファイルを以下のように編集します。
defmodule EctoModelsSample.Repo.Migrations.RemoveAgeToUsers do
use Ecto.Migration
def change do
alter table(:users) do
remove :age
end
end
end
マイグレーションします。
>mix ecto.migrate
[info] == Running EctoModelsSample.Repo.Migrations.RemoveAgeToUsers.change/0 forward
[info] alter table users
[info] == Migrated in 0.0s
3. まとめ
難しくないですね。
他の処理もEctoのドキュメントを参照すれば大体問題ないと思います。
毎回こうすんなり終わると楽でいいのだが・・・
参考文献
Phoenix Framework - Guide Mix Tasks
hexdocs - Ecto.Migration