LoginSignup
27
23

More than 5 years have passed since last update.

Phoenix と ecto(PostgreSQL) を連携してみる

Last updated at Posted at 2015-06-03

初期設定

Phoenix を使っている場合すでに config/dev.exs に設定されている模様。
PostgreSQL が嫌なときは new するときに --mysql でMySQLで設定できるらしい。

root/config/dev.exs
# Configure your database
config :app_name, app_name.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: "postgres",
  password: "postgres",
  database: "app_name_dev",
  size: 10 # The amount of database connections in the pool

ectoコマンド

ecto で使用できるコマンド類は mix に定義されているっぽい。

zsh
$ mix -h | grep ecto
mix ecto.create         # Create the storage for the repo
mix ecto.drop           # Drop the storage for the repo
mix ecto.gen.migration  # Generate a new migration for the repo
mix ecto.gen.repo       # Generate a new repository
mix ecto.migrate        # Run migrations up on a repo
mix ecto.rollback       # Rollback migrations from a repo

DBの作成

mix ecto.create でDBを作ってくれるっぽい。

zsh
$ mix ecto.create                                                                                                                                 
Compiled web/models/repo.ex
Compiled lib/app_name.ex
Compiled web/web.ex
Compiled lib/app_name/repo.ex
Compiled web/router.ex
Compiled web/controllers/page_controller.ex
Compiled web/views/error_view.ex
Compiled web/views/page_view.ex
Compiled lib/app_name/endpoint.ex
Compiled web/views/layout_view.ex
Generated app_name app
The database for app_name.Repo has been created.

# テスト用DB作成
$ env MIX_ENV=test mix ecto.create
postgresql
postgres=# \l
 app_name_dev | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
 app_name_test | postgres | UTF8     | en_US.utf8 | en_US.utf8 |

できてるっぽい。

modelの作成

ecto じゃなくて phoenix の方に定義されているっぽい。

zsh
$ mix phoenix.gen.model Tablename column1:string column2:text

mix ecto.migrate でmigrate

参考とか

27
23
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
27
23