0

Hey I am trying to make a query, my code look like this:

  def show(conn, _params) do
user = Guardian.Plug.current_resource(conn)
team = Web.get_team!(user.team.id)

score_query =
  from(
    u in User,
    where: u.team.id == team.id,
    select: sum(u.score)
  )

team_score = Repo.all(score_query)

IO.puts("score")
IO.inspect(team_score)

conn |> render("team.json", team: team)

And when I try to run it, I am getting an error that says:

** (Ecto.Query.CompileError) unbound variable `team` in query

but why is that unbound? How can I fix it and why is it happening?

Onorio Catenacci
  • 14,607
  • 14
  • 81
  • 126
jhonathan myers
  • 105
  • 1
  • 1
  • 12

1 Answers1

6

You should pin (^) team.id:

score_query =
  from(
    u in User,
    #                   ⇓ HERE
    where: u.team.id == ^team.id,
    select: sum(u.score)
  )

As per Ecto.Query documentation:

External values and Elixir expressions can be injected into a query expression with ^:

def with_minimum(age, height_ft) do
  from u in "users",
    where: u.age > ^age and u.height > ^(height_ft * 3.28),
    select: u.name
end
Aleksei Matiushkin
  • 113,340
  • 9
  • 96
  • 151