find_or_create with Ecto

The Ecto library in Elixir apparently does not have a native find_or_create method comparable to Activerecord as of the time of this writing. However, here is a nifty method you can drop into one of your Ecto models to achieve this behavior.

In the following example, we want to find or create by the user’s email.

def find_or_create(user) do
query = from u in User,
where: == ^ || Repo.insert!(user)

Thanks to info found here!

Posted in Uncategorized
2 comments on “find_or_create with Ecto
  1. Richard McIntyre says:

    I think the problem with this approach is that you are in fact wasting DB calls as in the case the record exists you are calling `` which is not efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *