Search code examples
elixirecto

"Variable does not exist" when I'm try to make a query with Ecto


I'm beginner in Elixir, and I'm trying to make a query, with:

def posts_liked(%{id: id}, _info) do
  query = from u in Like, where: u.user_id == ^id
  {:ok, Repo.all(query)}
end

But, say that the variable u doesn't exists. But, in oficial doc have this same code, and other manuals too. How to fix it?

My Like scheme is:

schema "likes" do
  belongs_to :post, Myapp.Post, foreign_key: :post_id
  belongs_to :user, Myapp.User, foreign_key: :user_id

  timestamps()
end

Solution

  • My guess is that you're missing import Ecto.Query in this module. Without that, Ecto thinks from is a normal function, not a macro, and starts checking that the arguments are valid. The first argument is u in Like, which desugars to Enum.member?(Like, u). Like is a valid value but there's no variable named u and Elixir throws that error. Adding

    import Ecto.Query
    

    or

    import Ecto.Query, only: [from: 2]
    

    to the module will fix this problem.