LoginSignup
21
21

More than 5 years have passed since last update.

[Phoenix]Ectoを使って再マイグレーションする

Last updated at Posted at 2015-06-30

目的

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の項目を追加/削除してみる。

現在のDBの状態。
re_migration001.png

目次

  1. カラム追加
  2. カラム削除
  3. まとめ

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

DBのusersテーブルを確認してみて下さい。
re_migration002.png

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

これで削除完了です。
re_migration001.png

3. まとめ

難しくないですね。
他の処理もEctoのドキュメントを参照すれば大体問題ないと思います。

毎回こうすんなり終わると楽でいいのだが・・・

参考文献

Phoenix Framework - Guide Mix Tasks
hexdocs - Ecto.Migration

21
21
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
21
21