首页 > 解决方案 > 视图中未定义的函数 conn/0

问题描述

我正在阅读 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,则项目编译(尽管由于明显的原因它无法呈现视图)。我对凤凰和灵药比较陌生,所以这很令人困惑。

标签: elixirphoenix-framework

解决方案


如果我添加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--not user_view.ex。您是否在发布所有输出后发布$ mix phx.server

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

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

../rumbl$ rm -rf _build

然后做:

../rumbl$ mix phx.server 

和 mix 将重建你的项目,_build在这个过程中重建目录。


推荐阅读