I’ve been working with Ecto a bit more lately, but I’ve not yet found a good way to do conditional updates on the query passed to repo, when dealing with optional parameters that are passed in. In the simple example below, I maybe be passed the active
and sort
query parameters, and the following is how I’m handling it, but I’d imagine that there must be a better and more concise way. Your help is appreciated
def index(conn, params) do
query = from u in Users
query =
case Map.get(params, "active") do
"true" ->
Users.active(query)
_ ->
query
end
query =
case Map.get(params, "sort") do
"asc" ->
User.sort(query, :asc)
"desc" ->
User.sort(query, :desc)
_ ->
query
end
users = Repo.all(query, conn: conn)
conn
|> Plug.Conn.put_resp_header("cache-control", "public, max-age=3600")
|> render("index.json", users: users)
end
In my mind, I was hoping for something like this…
def index(conn, params) do
query =
Users
|> Users.active if Map.get(params, "active") == true
|> Users.sort(Map.get(params, "sort")) if Map.has_key?(params, "sort")
users = Repo.all(query, conn: conn)
conn
|> Plug.Conn.put_resp_header("cache-control", "public, max-age=3600")
|> render("index.json", users: users)
end
A consideration that I have is multiple function clauses…