Ecto get_by returns nil?

Why does Ecto’s Repo.get_by returns nil. Example

dizzy = Repo.get_by(Artist, name: "Dizzy Gillespie")

iex(1) dizzy

So if you’re on Ecto 3.x (I’m looking at Ecto 3.2.5 documentation now), Repo.get_by returns nil under the following condition:

Returns nil if no result was found. Raises if more than one entry.

This means that your database doesn’t contain an “Artist” with an entry whose name is Dizzy Gillespie.

Can you do a Repo.all to see what data you have in the Artists table?

I just added an Artist with,

Repo.insert(%Artist{name: "Dizzy Gillespie"})

Then checked by
Repo.aggregate(Artist, ;count, :id)

and indeed it was added. So it contains the artist. Still the get_by result is nil.

Yes it’s all there, but why the variable containing the result of Repo.get_by returns nil?

Are you sure that there was no other entry in the DB? What is the return value od Repo.all(Artist)?

Isn’t there some tricky utf8 character somewhere?

Like I said the expected values are there, just wondering the meaning of get_by 's return value of nil?

@treble37 pointed you to the documentation fragment:

Returns nil if no result was found. Raises if more than one entry.

What do you want to know more?

1 Like

There is exactly 1 matching entry, so why nil?

If it’s nil then there is not one matching entry, something about the lookup is incorrect.