You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Phoenix MVC中Routes.hello_path/3未定义问题求助

Phoenix框架中Routes模块未找到导致UndefinedFunctionError的解决方案

访问GET /hello时触发UndefinedFunctionError,错误提示:function Routes.hello_path/3 is undefined (module Routes is not available),错误发生在index.html.heex文件中。

环境信息

└─$ elixir -v
Erlang/OTP 27 [erts-15.1] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit:ns]
Elixir 1.17.0 (compiled with Erlang/OTP 25)

项目结构

lib/
  hello/
  hello-web/
    components/
    controllers/
      hello_html/
        index.html.heex
        show.html.heex
      page_html/
      hello_controller.ex
      hello_html.ex
      page_controller.ex
      page_html.ex
    endpoint.ex
    gettext.ex
    router.ex
    telemetry.ex

解决方案

1. 修正模板中的路由引用

Phoenix默认没有全局的Routes模块,路由助手属于HelloWeb.Router.Helpers。解决方式有两种:

  • 直接使用完整模块名:将模板中的Routes.hello_path/3替换为HelloWeb.Router.Helpers.hello_path(conn, :show, your_id)
  • 设置别名简化调用:在hello_web.ex的view宏中添加别名定义,这样模板中可以继续用Routes.xxx的写法:
    def view do
      quote do
        # 保留原有代码...
        alias HelloWeb.Router.Helpers, as: Routes
      end
    end
    

2. 确认路由定义与助手元数匹配

打开router.ex,确保路由定义正确,且与模板中调用的函数元数对应:

scope "/", HelloWeb do
  pipe_through :browser

  get "/hello", HelloController, :index  # 对应hello_path/2
  get "/hello/:id", HelloController, :show  # 对应hello_path/3
end

如果模板中调用hello_path/3但未定义带参数的路由,也会触发错误。

3. 重新编译项目

执行命令清理缓存并重新编译,确保模块变更生效:

mix clean && mix compile

4. 检查View模块的导入配置

如果选择直接在模板中使用短名(如hello_path),需要在hello_web.ex的view宏中导入对应助手:

def view do
  quote do
    # 保留原有代码...
    import HelloWeb.Router.Helpers, only: [hello_path: 2, hello_path: 3]
  end
end

这样模板中无需前缀,直接写hello_path(conn, :index)或hello_path(conn, :show, 1)即可。

内容的提问来源于stack exchange,提问作者WireChuck Kraken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:34:53