【问题标题】:function nil.id/0 is undefined or private - Elixir函数 nil.id/0 未定义或私有 - Elixir
【发布时间】:2017-05-16 21:31:56
【问题描述】:

我正在尝试使用监护人身份验证来测试用户 ID 是否等于资源 ID。如果没有当前令牌并且我尝试转到正在检查令牌的 url,我会收到此错误 function nil.id/0 is undefined or private。我来自红宝石背景,我不知道为什么它说.id 是一个函数?以及为什么这会引发错误。这是我的代码:

def index(conn, %{"user_id" => user_id}) do
    user = Repo.get(User, user_id)
           |> Repo.preload(:projects)
    cond do
      user.id == Guardian.Plug.current_resource(conn).id ->
        conn
        |> render("index.html", projects: user.projects, user: user)
      :error ->
        conn
        |> put_flash(:info, "No access")
        |> redirect(to: session_path(conn, :new))
    end
  end

如果没有 current_resource 则打印此错误。但是如果没有 current_resource 我只想让它继续到 :error 路径并呈现会话路径。

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    这是因为您调用的是Guardian.Plug.current_resource(conn).id,而Guardian.Plug.current_resource(conn)nil。由于nil 是Elixir 中的一个Atom,模块也是,所以它上面的.id 尝试调用名为nil 的模块上的函数id(它不存在)。要解决此问题,您可以添加另一个检查以查看 Guardian.Plug.current_resource(conn) 是否不为零:

    cond do
      (resource = Guardian.Plug.current_resource(conn)) && user.id == resource.id ->
        conn
        |> render("index.html", projects: user.projects, user: user)
      :error ->
        conn
        |> put_flash(:info, "No access")
        |> redirect(to: session_path(conn, :new))
    end
    

    【讨论】:

    • 感谢您的帮助,我认为您是对的,但是当我更改您的代码时出现此错误。 web/controllers/admin/project_controller.ex:12: undefined function resource/0。那是我将行更改为resource == Guardian.Plug.current_resource(conn) && user.id = resource.id
    • 抱歉忘记标记你
    • 那是resource =,不是==
    • 是的。我还必须将它设置在 cond do 之上。否则我会收到此错误web/controllers/admin/project_controller.ex:12: undefined function resource/0。感谢您的帮助
    • resource = Guardian.Plug.current_resource(conn) cond do user.id == resource.id ->
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多