Workshop #1 Contexts and Generators - dgoldie/phoenix1.3_workshop GitHub Wiki

Workshop #1 - In this first workshop we focused on many new features. Here we list some lessons learned.

Created DevApp

Contexts

Basically, the methods to access the resource go in the context rather than the schema.

New Generators

Generating a resource without attributes creates tests that fail.

$ mix help phx.gen.html Accounts User users

Best to add attributes:

mix phx.gen.html Accounts User users name:string email:string bio:string number_of_pets:integer

JSON Api with Fallback Controller

The Fallback controller is very useful and seems straight forward. Creating a separate controller for API calls seemed best.

There is a question about the best way to handle a 404 from a show action. The generator created a get_user! method that calls a Repo.get!.

It seemed to work better with a Repo.get, so we added a different getter.

#/accounts/account.ex
  def get_user!(id), do: Repo.get!(User, id)
  def get_user(id) do
  case Repo.get(User, id) do
     nil  -> {:error, :not_found}
     user -> {:ok, user}
   end
#/api/user_controller.ex
  def show(conn, %{"id" => id}) do
    with {:ok, %User{} = user} <- Accounts.get_user(id),
    do: render(conn, "show.json", user: user)
  end

Test Watch

Add the library, then run in a separate terminal mix test.watch