Created
June 9, 2018 03:50
-
-
Save gugahoa/9c35b108f164538ac7723193ebee8138 to your computer and use it in GitHub Desktop.
get_or_create_category_by_name
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 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