【问题标题】:Undefined function conn/0 in View视图中未定义的函数 conn/0
【发布时间】:2019-10-14 04:50:56
【问题描述】:

我正在阅读 Programming Phoenix 1.4 这本书,在为用户创建视图时遇到了一个问题。我不断收到编译错误提示

== Compilation error in file lib/rumbl_web/views/user_view.ex ==
** (CompileError) lib/rumbl_web/views/user_view.ex:3: undefined function conn/0
    (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:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:208: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6`

尝试编译和运行项目时。 这是有问题的观点:

defmodule RumblWeb.UserView do
  use RumblWeb, :view
  alias Rumbl.Accounts

  def first_name(%Accounts.User{name: name}) do
    name
    |> String.split(" ")
    |> Enum.at(0)
  end

  def username(%Accounts.User{username: username}) do
    username
  end

end

如果我注释掉use RumblWeb, :view 行,项目将编译(尽管由于显而易见的原因它无法呈现视图)。我对凤凰和丹药比较陌生,所以这很令人困惑。

【问题讨论】:

  • 能否请您显示RumbleWeb mudule 的view/1 函数?
  • @JustinWood,rumbl_web.ex 中没有view/1 函数,它是view/0 函数。
  • 对。错字。还是想看看函数定义。
  • @JustinWood,我无法通过将 conn 添加到 view() 函数(或文件中的任何其他位置)来得到该错误。错误将指向rumbl_web.ex,但操作的错误消息显示错误在user_view.ex 中。如果操作员发布文件不会受到伤害 - 然后我可以将其与我的比较。

标签: elixir phoenix-framework


【解决方案1】:

如果我将conn 添加到views/user_view.ex 的第三行:

defmodule RumWeb.UserView do
  use RumWeb, :view
  conn  #====== *** HERE ***
  alias Rum.Accounts.User

  def first_name(%User{name: name} ) do
    name
    |> IO.inspect 
    |> String.split(" ")
    |> Enum.at(0)
  end


end

我遇到的错误几乎和你一样:

$ mix phx.server
Compiling 9 files (.ex)
warning: variable "conn" does not exist and is being expanded to "conn()", please use parentheses to remove the ambiguity or change the variable name
  lib/rum_web/views/user_view.ex:3


== Compilation error in file lib/rum_web/views/user_view.ex ==
** (CompileError) lib/rum_web/views/user_view.ex:3: undefined function conn/0
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:198: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

我的错误中没有以下内容:

ensure_no_undefined_local/3-

但这可能是由于长生不老药版本的差异。

如果我将conn 放在rumbl_web.ex 中的任何位置,则错误指向rumbl_web.ex--而不是user_view.ex。你是在$ mix phx.server之后发布所有的输出吗?

您确定您没有打开两个窗口并使用两个不同版本的文件user_view.ex?我会关闭您编辑器的所有窗口,然后重新打开您的项目并再次查看user_view.ex

有一次我遇到了一个奇怪的错误,解决方法是:

../rumbl$ rm -rf _build

然后做:

../rumbl$ mix phx.server 

并且 mix 将重建您的项目,在此过程中重新创建 _build 目录。

【讨论】:

  • 这与 OP 显示的堆栈跟踪不同。你的报告说它在 eex 文件中。 OP 说它在视图文件中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
相关资源
最近更新 更多