Skip to content

Instantly share code, notes, and snippets.

@LostKobrakai
Last active September 12, 2017 09:56
Show Gist options
  • Save LostKobrakai/7f71888cf3b7b32615d950db5a832f5a to your computer and use it in GitHub Desktop.
Save LostKobrakai/7f71888cf3b7b32615d950db5a832f5a to your computer and use it in GitHub Desktop.
medium post
defmodule App.RegistrationController do
use App.Web, :controller
alias App.{Registration, Repo}
def new(conn, _params) do
changeset = Registration.changeset(%Registration{})
render conn, :new, changeset: changeset
end
def create(conn, %{"registration" => registration_params}) do
case Registration.handle_registration(registration_params) do
{:ok, _} ->
redirect conn, to: registration_path(conn, :new)
{:error, _operation, error_changeset, _changes} ->
changeset =
Registration.changeset(%Registration{})
|> copy_errors(error_changeset)
render conn, :new, changeset: %{changeset | action: :insert}
end
end
defp copy_errors(to, from) do
Enum.reduce from.errors, to, fn {field, {msg, additional}}, acc ->
Ecto.Changeset.add_error(acc, field, msg, additional: additional)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment