Search code examples
phoenix-frameworkecto

Ecto.Queryable not implemented for [....]


I have the same error as Fix protocol Ecto.Queryable not implemented error but with what I think are different circumstances

I want to (following the Phoenix book) limit the Estimates that can be deleted to those owned by a user, except if they have Admin rights.

  def delete(conn, %{"id" => id}, user) do
    user_estimates =
        case user.customer_id == 1 do
            true ->
                IO.inspect("Admin")
                Repo.all(Estimate)
            false ->
                IO.inspect("Non-Admin")
                assoc(user, :estimates)
        end
    estimate = Repo.get!(user_estimates, id)
    Repo.delete!(estimate)

But when I use this function as an Admin I get

** (Protocol.UndefinedError) protocol Ecto.Queryable not implemented for [list of all Estimates]

What am I misunderstanding?


Solution

  • The problem is in

    Repo.all(Estimate)
    

    Repo.all actually executes the query passed and returns the results as a list. If you want an Ecto.Queryable that contains all estimates, just return Estimate.

    This should work:

    user_estimates =
      case user.customer_id == 1 do
        true ->
          IO.inspect("Admin")
          Estimate
        false ->
          IO.inspect("Non-Admin")
          assoc(user, :estimates)
      end