【发布时间】: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