Skip to content

Instantly share code, notes, and snippets.

@bongole
Last active February 29, 2016 12:17
Show Gist options
  • Save bongole/2226abd14b35cb17d851 to your computer and use it in GitHub Desktop.
Save bongole/2226abd14b35cb17d851 to your computer and use it in GitHub Desktop.
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