具有两个参数

时间:2016-10-01 23:41:42

标签: routes phoenix-framework

我在Phoenix应用程序中创建了一个名为ProgressController的控制器。这是我的路由器文件的样子:

defmodule MyTestApp.Router do
  use MyTestApp.Web, :router

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", MyTestApp do
    pipe_through :api

    get "/users/:user_id/courses/:course_id", ProgressController, :show
  end
end

当我运行mix phoenix.routes时,它输出:

progress_path  GET   /users/:user_id/courses/:course_id  MyTestApp.ProgressController :show

我有以下测试,它使用progress_path

test "shows the user's progress in the given course", %{conn: conn} do
  # prepare some stuff
  conn = get conn, progress_path(conn, :show, %{user_id: 1, course_id: 7})
  # assert some stuff
end

progress_pathmix phoenix.routes给我的名称相同,我很惊讶在运行测试时会看到此错误消息:

编译11个文件(.ex)

** (CompileError) test/controllers/progress_controller_test.exs:12: undefined function progress_path/3
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/code.ex:363: Code.require_file/2
    (elixir) lib/kernel/parallel_require.ex:57: anonymous fn/2 in Kernel.ParallelRequire.spawn_requires/5

20:34:46.402 [error] GenServer #PID<0.242.0> terminating
** (CompileError) test/controllers/progress_controller_test.exs:12: undefined function progress_path/3
    (stdlib) lists.erl:1338: :lists.foreach/2
    (elixir) src/elixir_module.erl:113: :elixir_module.do_compile/5
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) src/elixir.erl:223: :elixir.erl_eval/3
    (elixir) src/elixir.erl:211: :elixir.eval_forms/4
    (elixir) src/elixir_compiler.erl:66: :elixir_compiler.eval_compilation/3
    (elixir) src/elixir_lexical.erl:17: :elixir_lexical.run/3
    (elixir) src/elixir_compiler.erl:30: :elixir_compiler.quoted/3
    (elixir) lib/code.ex:363: Code.require_file/2
    (elixir) lib/kernel/parallel_require.ex:57: anonymous fn/2 in Kernel.ParallelRequire.spawn_requires/5

我将问题缩小到这条路线的URL中有2个参数的事实,但我无法弄清楚如何实际解决这个问题。我做错了什么?

2 个答案:

答案 0 :(得分:5)

经过大量的搜索,试验和错误后,我发现path函数需要一个params列表,而不是Map。像这样:

conn = get conn, progress_path(conn, :show, 1, 7)

答案 1 :(得分:1)

我查看了最后的文档后发现了一个解决方案。

要使用path_helper,必须设置:

Routes.page_path(@conn, :name)