【问题标题】:Filtering results json with query params phoenix使用查询参数 phoenix 过滤结果 json
【发布时间】:2019-09-10 15:05:51
【问题描述】:

我尝试创建一个允许用户使用用户名和电子邮件过滤或创建请求的 REST API。

第一个 URL 返回完整的用户列表 http://localhost:4000/api/users

第二个应该适合数据 http://localhost:4000/api/users?email=XXX&username=YYY

我尝试使用两种方法来解决这个问题:

  def index(conn, _params) do
    users = Res.list_users()
    render(conn, "index.json", users: users)
  end

  def search_user(username, email) do
    Repo.one(from t in User, where: t.username == username and t.email == email, select: t, limit: 1)
    render(conn, index.json, users: users)
  end

运行时返回错误:

controllers/user_controller.ex:15: undefined function from/2
Console output is shown below.
Compiling 1 file (.ex)

== Compilation error in file lib/app_web/controllers/user_controller.ex ==
** (CompileError) lib/app_web/controllers/user_controller.ex:15: undefined function from/2
    (elixir) src/elixir_locals.erl:108: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
(elixir) src/elixir_locals.erl:108: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
(stdlib) erl_eval.erl:680: :erl_eval.do_apply/6
(elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/

谢谢

【问题讨论】:

  • 您需要import Ecto.Query 才能访问from/2 宏。您还需要使用t.username == ^username and t.email == ^email。您可以删除 select: t 部分,因为这是自动的。您也没有分配 Repo.one/2 并且当前在该范围内没有 users 变量。
  • 是的,你是对的!我更新了上面的代码,但我仍然有一个问题。感谢您帮助我进行这项“改进”!=
  • 您使用的是同一个端点。您将需要将search_user 更改为/api/users/search 或其他内容。您需要在 router.ex 文件中执行此操作。
  • 我会这样做,即使这不是我们想要的......
  • 不得根据您获得的建议修改问题。原始问题应该保持不变,以便未来的访问者了解上下文。

标签: elixir phoenix-framework crud


【解决方案1】:

如果要保持端点相同,可以执行以下操作

def index(conn, %{"username" => username, "email" => email}) do
  users = Repo.one(from t in User, where: t.username == ^username and t.email == ^email, select: t, limit: 1)
  render(conn, "filter.json", users: users)
end
def index(conn, _params) do
  users = Res.list_users()
  render(conn, "index.json", users: users)
end

现在,这将处理当您有用户名和电子邮件参数时以及当您没有这两个参数时的场景。

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 2015-03-27
    • 2022-10-14
    • 1970-01-01
    • 2012-04-20
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多