Skip to content

Instantly share code, notes, and snippets.

@marka2g
Forked from slashdotdash/upsert_profile.ex
Created July 26, 2020 23:09
Show Gist options
  • Select an option

  • Save marka2g/7f5beae4ca0183efc472eebc8dd2ecfa to your computer and use it in GitHub Desktop.

Select an option

Save marka2g/7f5beae4ca0183efc472eebc8dd2ecfa 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment