我在Phoenix app控制器中执行了以下操作:
defmodule TattooBackend.Web.API.V1.StudioController do
use TattooBackend.Web, :controller
alias TattooBackend.Repo
alias TattooBackend.Accounts.Account
def index(conn, params) do
studios = Studio
studios = if params["search"] do
Studio.search(studios, params["search"])
end
studios = studios |> Repo.all |> Repo.preload(:address)
render conn, studios: studios
end
end
有没有办法重构这段代码以使其更具可读性?
答案 0 :(得分:2)
当params["search"]
是假的时,您的代码将无法运作。如果是假的,studios
将获得值nil
。
你可以更优雅地做到这一点:
studios =
if params["search"] do
Studio.search(Studio, params["search"])
else
Studio
end
|> Repo.all
|> Repo.preload(:address)
if
也可以折叠成一行:
studios =
if(params["search"], do: Studio.search(Studio, params["search"]), else: Studio)
|> Repo.all
|> Repo.preload(:address)
答案 1 :(得分:1)
您可以通过reduce
在参数上构建更复杂的查询,例如允许有条件地包含地址:
query =
Enum.reduce(params, Studio, fn
{"search", search_term}, query -> Studio.search(query, search_term)
{"include_address", "true"}, query -> Ecto.Query.preload(query, :address)
# ... additional query building params handled here
_, query -> query # ignore unrecognised params
end)
studios = Repo.all(query)
render conn, studios: studios