Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Last active July 26, 2020 23:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slashdotdash/0ff19dead936ca3e370879a711b798c7 to your computer and use it in GitHub Desktop.
Save slashdotdash/0ff19dead936ca3e370879a711b798c7 to your computer and use it in GitHub Desktop.
Upserts in Ecto using `Ecto.Multi`
defp upsert_profile(multi, source, source_uuid, profile_url) do
profile = %Profile{
source: source,
source_uuid: source_uuid,
profile: profile_url,
}
Ecto.Multi.insert(multi, source_uuid, profile, on_conflict: [set: [profile: profile_url]], conflict_target: [:source, :source_uuid])
end
# usage
members
|> Enum.reduce(Ecto.Multi.new, fn (member, multi) -> upsert_profile(multi, "athlete", member.athlete_uuid, member.profile) end)
|> Repo.transaction
@slashdotdash
Copy link
Author

slashdotdash commented Jan 12, 2017

Example given is using PostgreSQL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment