【问题标题】:How to resolve lib/.../views/user_view.ex:16: undefined function user_path/3 compilation error如何解决 lib/.../views/user_view.ex:16: undefined function user_path/3 编译错误
【发布时间】:2019-04-09 09:24:01
【问题描述】:

尝试添加用户视图和用户控制器,但我遇到了一个奇怪的编译错误。

通过查看Programming Phoenix: undefined function page_path/2 我怀疑这也与生成的文件有关,但我仍然不明白如何解决它

这是我在控制器文件夹中的 user_controller.ex:

defmodule ChatterWeb.UserController do
  use ChatterWeb, :controller
  alias Chatter.User

  def index(conn, _params) do
    users = Repo.all(User)
    render(conn, "index.html", users: users)
  end
end

这是我在视图文件夹中的 user_view.ex:

defmodule ChatterWeb.UserView do
  use ChatterWeb, :view
end

这是我的 router.ex 中的路由部分:

  scope "/", ChatterWeb do
    pipe_through :browser
    resources "/users", UserController
    get "/", PageController, :index
  end

这是我的 user.ex(有架构):

defmodule Chatter.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :email, :string
    field :encrypt_pass, :string
    field :password, :string, virtual: true

    timestamps()
  end

  @doc false
  def changeset(user, attrs) do
    user
    |> cast(attrs, [:email, :password])
    |> validate_required([:email, :password])
    |> unique_constraint(:email)
  end
end

这是我在编译时遇到的错误:

== Compilation error in file lib/chatter_web/views/user_view.ex ==
** (CompileError) lib/chatter_web/views/user_view.ex:16: undefined function user_path/3
    (elixir) src/elixir_locals.erl:107: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
    (elixir) src/elixir_locals.erl:107: 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:208: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

如果文件只有 3 行代码,我不明白为什么会说 ex:16。我猜use 关键字会从不同的文件中注入代码,但这使得很难确定它到底哪里出了问题。

【问题讨论】:

  • 通过在 user_controller、router 和 user_view 文件中将名称 user 更改为 userp,一切正常。但是,当我将模板文件的名称从 user 更改为 userp 时,我得到了 == Compilation error in file lib/chatter_web/views/user_view.ex == 的错误,所以我很确定它与控制器上的渲染有关(我认为)
  • tbh 这仍然不能解决任何问题,当我访问localhost:4000/users 时,我只是收到另一个错误消息Could not render "index2.html" for ChatterWeb.UserView, please define a matching clause for render/2 or define a template at "lib/chatter_web/templates/user". No templates were compiled for this module.,当然正确命名文件会导致我回到上一个错误

标签: elixir phoenix-framework


【解决方案1】:

显然,lib/chatter_web/views/user_view.ex:16 中的ex:16 实际上指的是lib/chatter_web/templates/user/index.html.eex。我不明白为什么。但是在那个文件中,当它应该是 Routes.user_path(@conn, :show, user) 时,我指的是 user_path(@conn, :show, user)。从Undefined [controller]_path for route with two params 了解到这一点(我相信这是由于 1.4.3 文档)

【讨论】:

  • 感谢@Schrockwell,“查看模块实际上采用.eex 文件,并使用宏的魔力将它们包装为模块中的普通旧函数。除了您在模块中定义的任何函数. 所以这就是为什么行号很奇怪......他们指的是在编译时生成的 Elixir 语法”
猜你喜欢
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 2018-03-19
相关资源
最近更新 更多