Building Relationships Programming Phoenix

The problem is in the command iex -S mix phoenix.server

When I do
import Ecto.Query user = Repo.get_by!(User, username: "test")
I get
** (UndefinedFunctionError) undefined function Repo.get_by!/2 (module Repo is not available) Repo.get_by!(User, [id: "1"])
What should I do ?

1 Like

You need to include alias YourApp.Repo your include the whole Module name
when calling the function.

4 Likes

That’s because your current module doesn’t have Repo module in it. I believe you’re referencing to Phoenix.Repo which is need to be included in your module. You can do that by adding alias YourApp.Repo in your module and call the function like you did or directly call the function like this YourApp.Repo.get_by!(User, username: "test"). You will see a lot of code using alias instead of referencing the full name. That will solve the problem.

2 Likes

Thank you ! I will test that when I can !

1 Like

As others have pointed out, you don’t have your aliases set for these modules. One thing you can do to make your iex experience nicer is to configure iex to auto-alias the things you commonly use.

In your root directory create a file .iex.exs and add some stuff to it:

import Ecto.Query
import Foo.Repo
import Foo.User
3 Likes