Skip to content

Instantly share code, notes, and snippets.

@whazzmaster
Created September 20, 2017 15:02
Show Gist options
  • Save whazzmaster/3b5d8d60eeb9bee2464ce3b23617fe60 to your computer and use it in GitHub Desktop.
Save whazzmaster/3b5d8d60eeb9bee2464ce3b23617fe60 to your computer and use it in GitHub Desktop.
Associating Two Records in a Many-to-Many Relationship
defmodule Identity do
# ...
defp link_user_and_company(user = %User{}, company = %Company{}) do
user = Repo.preload(user, :companies)
companies = user.companies ++ [company]
|> Enum.map(&Ecto.Changeset.change/1)
user
|> Ecto.Changeset.change
|> Ecto.Changeset.put_assoc(:companies, companies)
|> Repo.update
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment