LoginSignup
2

More than 5 years have passed since last update.

Phoenixとかectoとかの備忘録

Last updated at Posted at 2016-10-14

Phoenixとかectoとかの備忘録

controllerでoptionalな引数を取る

def create(conn, %{"name" => name, "password" => password} = params) do
  avatar_image = Map.get(params, "avatar_image", "default_image")

  # ...
end

preloadされていない判定

%Ecto.Association.NotLoaded{} でマッチできる。

case Map.get(model, assoc) do
  %Ecto.Association.NotLoaded{} ->
    false
  _ ->
    true
end

テストコードでIEx.pry

一定時間以上停止してるとDBコネクションが切れるので、config/test.exsに設定を追加する。

config :logger, :console, format: "[$level] $message\n", ownership_timeout: :infinity

テスト実行する時に --trace つける必要があるかも。

mix task

configをmixtaskからでも参照できるようにする

Mix.Task.run "app.start"

DB操作をできるようにする

Repo.start_link()

ectoで複数の変数

クエリで定義(from hoge in query)した変数を複数使いたいことがある。
from [t, users_to_teams] in query にようにする。

defp get_all_for_member_count_order(query) do
  query = (from t in query,
    join: users_to_teams in assoc(t, :users_to_teams),
    group_by: t.id
  )
end

def get_all_by_asc_of_member_count(query) do
  #    ↓ ここをlistで定義する
  from [t, users_to_teams] in get_all_for_member_count_order(query), [
    order_by: [asc: count(users_to_teams.team_id)]
end

fromの後に二つ変数を用意しないと、意図しないデータからフィールドを参照しようとしてエラーになる。

def get_all_by_asc_of_member_count(query) do
  #    ↓ 単体だと意図しないデータが入る可能性
  from users_to_teams in all_for_member_count_order(query), [
    order_by: [asc: count(users_to_teams.team_id)]
end 
** (Postgrex.Error) ERROR (undefined_column): column t0.team_id does not exist

ややこしいやつ

Struct, Map, Tuple, List, Keyword List
http://elixir-lang.org/getting-started/keywords-and-maps.htm

%Struct{}, %{k: 1}, {1, 2}, [key: 1], [1, 2]

バージョン管理

asdf

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
2