-->

Fix protocol Ecto.Queryable not implemented error

2019-06-24 19:42发布

问题:

I'm new to using Ecto and Elixir and I've come across an error that I can't explain. My code looks just like the example in the Ecto README.

Here are my modules for the Ecto Model and Query

defmodule Registration do
  use Ecto.Model

  schema "registrations" do
    field :user_id, :string
    field :created_at, :datetime, default: Ecto.DateTime.local
    field :updated_at, :datetime, default: Ecto.DateTime.local
  end
end

defmodule RegistrationQuery do
  import Ecto.Query

  def by_user(user_id) do
    query = from r in Registration,
          where: r.user_id == ^user_id,
         select: r
    Repo.all(query)
  end
end

Here is how I call the query function

registrations = Repo.all RegistrationQuery.by_user("underwater")

This all seems exactly in line with the Ecto documentation, and I can't find anything saying otherwise. But I get the following error.

protocol Ecto.Queryable not implemented for [%Ensalutilo.Registration{user_id: "underwater"}]

回答1:

Your by_user/1 function is already calling Repo.all, so when you call registrations = Repo.all(...) later on, you are passing the result of the first Repo.all as argument, which is a list as you see in the error message!

To be clear, you get this error message because you can pass anything that implements the Ecto.Queryable protocol into Repo.all.