Last active
February 29, 2016 12:17
-
-
Save bongole/2226abd14b35cb17d851 to your computer and use it in GitHub Desktop.
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 EctoTest.Repo do | |
use Ecto.Repo, otp_app: :ecto_test | |
import Ecto.Query | |
def find_or_create_by(queryable, attrs) do | |
q = Enum.reduce(attrs, queryable, fn | |
{field, val}, query -> | |
query |> where([x], field(x, ^field) == ^val) | |
_, query -> query | |
end) | |
r = all(q) | |
if r == [] do | |
insert!(struct(queryable, attrs)) | |
else | |
hd(r) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment