Last active
November 20, 2021 12:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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