Last active
August 23, 2021 15:37
-
-
Save abitdodgy/8e79f0f2dc7358aef250012b338d1169 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.Registration do | |
use App.Web, :model | |
alias App.{Account, User, Membership, Repo} | |
embedded_schema do | |
field :email | |
field :org_name | |
end | |
@required_fields ~w(email org_name)a | |
def changeset(struct, params \\ %{}) do | |
struct | |
|> cast(params, @required_fields) | |
|> validate_required(@required_fields) | |
end | |
def to_multi(params \\ %{}) do | |
Ecto.Multi.new | |
|> Ecto.Multi.insert(:account, account_changeset(params)) | |
|> Ecto.Multi.insert(:user, user_changeset(params)) | |
|> Ecto.Multi.run :membership, fn changes -> | |
Repo.insert membership_changeset(changes) | |
end | |
end | |
defp account_changeset(%{"org_name" => org_name}) do | |
Account.changeset %Account{name: org_name} | |
end | |
defp user_changeset(params) do | |
user_params = Map.take(params, ["email"]) # ... name, password, etc... | |
User.changeset %User{}, user_params | |
end | |
defp membership_changeset(changes) do | |
%Membership{account_id: changes.account.id, | |
user_id: changes.user.id, | |
role: :admin} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment