wolfiton
Rewriting this where using private fn
I have the following function that I want to rewrite using the defp
def list_items(%{matching: name}) when is_binary(name) do
Item
|> where([m], ilike(m.name, ^"%#{name}%"))
|> Repo.all()
end
What I tried
def list_items(%{matching: name}) when is_binary(name) do
Item
|> search(term)
|> Repo.all()
end
defp search(term) do
term
|> from t in Item
|> where([t], ilike(t.name, ^"%#{term}%"))
end
Can someone explain how to do this?
from` must be a compile time keyword list
Shouldn’t Item work here?
Thanks
Most Liked
benwilson512
t is not a real variable, because where is not a function, it’s a macro. t is part of the syntax of the macro. Examples here: https://hexdocs.pm/ecto/Ecto.Query.html#where/3-expressions-example
The where macro basically just creates a t that you can use in the second part of where.
benwilson512
Yes. If you pipe a query struct into where, it grabs the schema you’re querying out of the query and makes it available as whatever variable you put in the list.
wolfiton
Final version using the advice from @benwilson512
def list_items(%{matching: name}) when is_binary(name) do
Item
# |> where([m], ilike(m.name, ^"%#{name}%"))
|> search(name)
|> Repo.all()
end
defp search(query, name) do
query
|> where([t], ilike(t.name, ^"%#{name}%"))
end
benwilson512
You’re overthinking my response, I’m saying you literally can just leave out the from:
defp search(query, name) do
query
|> where([t], ilike(t.name, ^"%#{name}%"))
end
benwilson512
term
|> from t in Item
This isn’t a valid way to use from, it expands to from(term, t in Item) since |> puts arguments at the front.







