函数nil.id/0是未定义的或私有的-Elixir [英] function nil.id/0 is undefined or private - Elixir

查看:91
本文介绍了函数nil.id/0是未定义的或私有的-Elixir的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to test if a user id is equal to the resource id using guardian auth. If there is no current token and I try to go to a url that is checking for a token I get this error function nil.id/0 is undefined or private. I come from a ruby background and I don't know why it's saying .id is a function? and why this is throwing an error. Here is my code:

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路径并呈现会话路径.

If there is no current_resource then it prints this error. But if there is no current_resource I just want it to continue to the :error path and render the session path.

推荐答案

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

This is because you're calling Guardian.Plug.current_resource(conn).id and Guardian.Plug.current_resource(conn) is nil. Since nil is an Atom in Elixir and so are modules, .id on it tries to call the function id on the module named nil (which doesn't exist). To fix this, you can add another check to see if Guardian.Plug.current_resource(conn) is not nil:

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

这篇关于函数nil.id/0是未定义的或私有的-Elixir的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆