I have a User
model with a has_many
relationship to other_model
.
I have a function Search
that searches the internet. What I would like to do is search the internet only if the has_many
relationship is not an empty array.
So I'm wondering if I can pattern match against a non-empty array? As you can see below, the extra Search
results in nested branch and hence I use the with
statement and am hoping for a clean solution.
query = from a in Model, where: a.id == ^id, preload: [:some_associations]
with %{some_associations: some_associations} <- Repo.one(query),
{:ok, some_results} <- Search.call(keywords, 1) do
do_something_with(some_associations, some_results)
else
nil -> IO.puts "query found nothing"
{:error, reason} -> IO.puts "Search or query returned error with reason #{reason}"
end
You can use the pattern [_ | _]
to match non-empty lists:
{:ok, some_results = [_ | _]} <- Search.call(keywords, 1)
iex(1)> with xs = [_|_] <- [1, 2, 3] do {:ok, xs} else _ -> :error end
{:ok, [1, 2, 3]}
iex(2)> with xs = [_|_] <- [] do {:ok, xs} else _ -> :error end
:error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With