My code is below. I get an error saying that the where and last methods are unavailable.
defmodule AppWeb.PageLive do
use AppWeb, :live_view
alias App.TestBeds
def mount(_params, _session, socket) do
TestBeds.list_testbeds|> where(name: "Zarnog") |> last(:inserted_at) |> IO.inspect
{:ok, assign(socket, testbeds: TestBeds.list_testbeds())}
end
end
I tried importing
import Ecto.Query
I got a big error.
protocol Ecto.Queryable not implemented for [%App.TestBeds.TestBed{__meta__: #Ecto.Schema.Metadata<:loaded, "testbeds">, id: 1, name: "Zarnog", note: "best testbed!", status_action_id: 1, version: "6.01", inserted_at: ~N[2023-03-01 18:35:30], updated_at: ~N[2023-03-01 18:35:30]}] of type List. This protocol is implemented for the following type(s): Atom, BitString, Ecto.Query, Ecto.SubQuery, Tuple
My goal is to understand how to do queries of the sort expressed in my code. I see different examples all over the web.
Try creating a new function on your TestBeds module that will retrieve the record you want, something like: App.TestBeds.TestBed |> where(name: "Zarnog") |> last(:inserted_at) |> App.Repo.one() (You could also just try this on an iex session and see how it goes)
Here you’ll be passing the schema you want to query from (App.TestBeds.TestBed) rather than a list of your existing TestBeds.
Your TestBeds.list_testbeds return a list of records. where, last and friends don’t know what to do with a list, they need a queryas the first argument.
If you look inside your lib/app folder, there will be a module named repo.ex.
It uses the Ecto.Repo from Ecto where you have some functions, including one which will fetch one record matching the query you passed to it.
There is also all function, which will fetch all the records matching your query (as probably the TestBeds.list_testbeds does).
There is more to it, but I don’t want to lead you on a rabbit whole, I think is best if you acquaint yourself with it on your own pace.
Reading the link I sent you about Repo will probably clarify some things.
Also, feel free to mark the answer as a solution if you want.
Repo.one is just a function call, there’s nothing special about that syntax. As for where you’re supposed to find out about that function, it’s covered in the Ecto docs Ecto.Repo — Ecto v3.9.4.