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
Hi , I kind of did this for my requirement. hope it helps you,
def search(params)
qfilters = reject_empty_values(params)
search_q = profile_q(qfilters)
(from p in search_q , where: p.id == 2) |> Repo.all
end
defp profile_query([]), do: Profile
defp profile_query(filters) do
from q in Profile, where: filters
end
def search(model, %{name: name} = params) do
model
|> search_q(name)
|> Repo.all
end
defp search_q(model, name) do
from m in model, where: m.name == name
end
No, I am rewriting this to suit my style and understand more how Ecto works with phoenix and absinthe. Also to make it more compos-able using the composition pattern.
def list_items(%{matching: name}) when is_binary(name) do
Item
|> where([m], ilike(m.name, ^"%#{name}%"))
|> Repo.all()
end
ahh, i get it. cool.
you are planning to |> search_by_name, search_by_age
def search(%{name: name, age: age} = params}) do
model
|> sname(name)
|> sage(age)
|> Repo.all
end
defp sname(query, name), do: from q in query, where: q.name == name
defp sage(query, age), do: from q in query, where: q.age == age
Hope it works,