Skip to content

Instantly share code, notes, and snippets.

@gugahoa
Created June 9, 2018 03:50
Show Gist options
  • Save gugahoa/9c35b108f164538ac7723193ebee8138 to your computer and use it in GitHub Desktop.
Save gugahoa/9c35b108f164538ac7723193ebee8138 to your computer and use it in GitHub Desktop.
get_or_create_category_by_name
defmodule Something do
def get_or_create_category_by_name(name) do
Repo.transaction(fn ->
case Repo.get_by(Category, name: name) do
{:ok, category} ->
category
_ ->
case create_category(%{name: name}) do
{:ok, category} -> category
{:error, error} -> Repo.rollback(error)
end
end
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment