-
-
Save johan--/bc092d0bcbb6517ea2336f0faef9d0f4 to your computer and use it in GitHub Desktop.
Find or Create in Ecto
This file contains hidden or 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
# two different ways to implement a find_or_create for Ecto | |
find_or_create_user = fn user -> | |
case Repo.all(from u in users, where: u.id == ^user.id and u.email == ^user.email) do | |
[] -> | |
%User{} | |
|> User.changeset(user) | |
|> Repo.insert!() | |
_ -> | |
IO.puts "Already inserted" | |
end | |
end | |
def find_or_create(user) do | |
query = from u in users, | |
where: u.uid == ^user.uid | |
if !Repo.one(query) do | |
Repo.insert(user) | |
end | |
Repo.one(query) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment