(Postgrex.Error) ERROR (undefined_table): relation "abstract table: addresses" does not exist was caused by an error that should be fixed in Ecto v1.0.3 or later.
In the above code, there is no identifier for the address, without this Ecto will insert a new resource instead of updating an existing one.
Request (PATCH):
{ "user" => { "address" => { "id" => 4, "street_address" => "1234" } } }
The new controller code, including some of JoseValims, has suggested improvements:
def update(conn, %{"id" => id, "user" => params}) do user = MyApp.Repo.get!(User, id) |> MyApp.Repo.preload [:address changeset = User.changeset(user, params) case MyApp.Repo.update(changeset) do {:ok, model} -> send_resp(conn, 204, "") {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(MyApp.ChangesetView, "error.json", changeset: changeset) end end
Or, in this situation, since the address is required and has_one , an identifier can be added on the server side:
def update(conn, %{"id" => id, "user" => params}) do user = MyApp.Repo.get!(User, id) |> MyApp.Repo.preload [:address] address = params["address"] address = Map.put address, "id", user.address.id params = Map.put params, "address", address changeset = User.changeset(user, params) case MyApp.Repo.update(changeset) do {:ok, model} -> send_resp(conn, 204, "") {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(MyApp.ChangesetView, "error.json", changeset: changeset) end end