LoginSignup
19
18

More than 5 years have passed since last update.

Elixir+Phoenix開発Tips

Posted at

Tipsというか、開発しててハマったりわかりにくかった点をいくつかあげてみたいと思います。

モデルのPrimaryKeyをデフォルトから変更する

mixコマンドで mix phoenix.gen.model User users name:string age:integer のようにモデルを生成して mix ecto.migrate を実行するとテーブルのPrimaryKeyはidで作られてしまいます。

これを別名のカラムにしたいときは以下の様にします。

1, mix phoenix.gen.model でモデル作成

command
$ mix phoenix.gen.model User users name:string age:integer

2, 作成された priv/repo/migrations/xxx_create_user.exs と web/models/user.ex を編集する

xxx_create_user.exs
defmodule Sample.Repo.Migrations.CreateUser do
  use Ecto.Migration

  def change do
    create table(:users, primary_key: false) do
      add :user_id, :string, primary_key: true
      add :name, :string
      add :age, :integer

      timestamps
    end
  end
end
user.ex
defmodule Sample.User do
  use Sample.Web, :model

  @primary_key {:user_id, :string, []}
  schema "users" do
    field :name, :string
    field :age, :integer

    timestamps
  end

  @required_fields ~w(user_id name age)
  @optional_fields ~w()
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

3, mix ecto.migrate を実行

preflightリクエスト対策

preflightリクエストとはクロスドメインアクセスが可能か確認するリクエストを送ることです。
詳細はこちらの記事などを参考に。

超ざっくり言えばOPTIONSメソッドでアクセスが来たらこの対応が必要と思っていただければ^^;

1, Corsica を追加する

depsに以下を追記して mix deps.get

mix.exs
defp deps do
  [{:corsica, "~> 0.4"}]
end

2, lib/xxx(プロジェクト名)/endpoint.ex に以下を追記

endpoint.ex
# originsに許可するホストを、allow_headersにアクセス時に許可するヘッダーを追加する
plug Corsica, [origins: ["http://localhost:8080"], allow_headers: ["accept", "content-type", "hogefuga", "origin"]]

ファイルアップロードの上限値を上げる

lib/xxx(プロジェクト名)/endpoint.ex を編集する

endpoint.ex
plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json],
  pass: ["*/*"],
  json_decoder: Poison,
  length: 104_758_600 # ここが上限値

Erlangの関数を使うとき・・・

Erlangの関数やライブラリを使うとき、文字は文字列ではなく文字リストで扱うことが多いです。
つまり "ほげ" ではなく 'ほげ' ですね。

引数に渡す文字や、返り値の文字に注意してください。これをつい忘れているとハマります・・・


とりあえずはこんなところです。
また出てきて知見が溜まったら書きます。

19
18
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
19
18