Skip to content

Instantly share code, notes, and snippets.

@pochi
Created October 21, 2014 08:58
Show Gist options
  • Save pochi/918bf1b1fbe380895af6 to your computer and use it in GitHub Desktop.
Save pochi/918bf1b1fbe380895af6 to your computer and use it in GitHub Desktop.
Phoenix application sample

Postgre SQLの設定

RailsでいうGemfileの設定。 postgrexとectoを追加。

defmodule Blog.Mixfile do
  use Mix.Project

  def project do
    [app: :blog,
     version: "0.0.1",
     elixir: "~> 1.0",
     elixirc_paths: ["lib", "web"],
     compilers: [:phoenix] ++ Mix.compilers,
     deps: deps]
  end

  # Configuration for the OTP application
  #
  # Type `mix help compile.app` for more information
  def application do
    [mod: {Blog, []},
     applications: [:phoenix, :cowboy, :logger, :postgrex, :ecto]]
  end

  # Specifies your project dependencies
  #
  # Type `mix help deps` for examples and options
  defp deps do
    [{:phoenix, "0.5.0"},
     {:cowboy, "~> 1.0"},
     {:postgrex, ">= 0.0.0"},
     {:ecto, ">= 0.0.0"}]
  end
end

データベース設定ファイルの追加

Railsでいうconfig/database.rb. 今回はlib/blog/repo.exに以下を作成した。

defmodule Repo do
  use Ecto.Repo, adapter: Ecto.Adapters.Postgres

  def conf do
    parse_url "ecto://pochi:pochi@localhost/phoenix_blog"
  end

  def priv do
    app_dir(:blog, "priv/repo")
  end
end

さらにlib/blog/supervisor.exを追加。

defmodule Blog.Supervisor do
  use Supervisor

  def start_link do
    :supervisor.start_link(__MODULE__, [])
  end

  def init([]) do
    tree = [worker(Repo, [])]
    supervise(tree, stragegy: :one_for_one)
  end
end

migration

まずはmigrationファイルを作る。 これはectoの機能。

$ mix ecto.gen.migration Repo create_users
Compiled lib/blog.ex
Compiled lib/blog/supervisor.ex
Compiled lib/blog/repo.ex
Generated blog.app
* creating priv/repo/migrations
* creating priv/repo/migrations/20141021035704_create_users.exs

上記コマンドでファイルが作成されるので まずはidとnameとemailを持つようデータを作成する。

priv/repo/migrations/20141021035704_create_users.exs

defmodule Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def up do
    "CREATE TABLE users(id serial primary key, name varchar(50), email varchar(50))"
  end

  def down do
    "DROP TABLE users"
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment