Skip to content

Instantly share code, notes, and snippets.

@abitdodgy
Last active November 20, 2021 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abitdodgy/31cb4fbd5ee28201d51abe48058c40c5 to your computer and use it in GitHub Desktop.
Save abitdodgy/31cb4fbd5ee28201d51abe48058c40c5 to your computer and use it in GitHub Desktop.
Medium Article: Building Many-To-Many Associations with Embedded Schemas in Ecto and Phoenix
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
changeset = Registration.changeset(%Registration{}, registration_params)
if changeset.valid? do
case Repo.transaction(Registration.to_multi(registration_params)) do
{:ok, _} ->
redirect conn, to: registration_path(conn, :new)
{:error, _operation, repo_changeset, _changes} ->
changeset = copy_errors(repo_changeset, changeset)
render conn, :new, changeset: %{changeset | action: :insert}
end
else
render conn, :new, changeset: %{changeset | action: :insert}
end
end
defp copy_errors(from, to) 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