函数 nil.id/0 未定义或私有 - Elixir

2024-01-12

我正在尝试使用监护人身份验证来测试用户 ID 是否等于资源 ID。如果没有当前令牌,并且我尝试访问正在检查令牌的网址,则会收到此错误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 路径并渲染会话路径。


这是因为你正在打电话Guardian.Plug.current_resource(conn).id and Guardian.Plug.current_resource(conn) is nil. Since nilElixir 中的 Atom 是 Atom,模块也是 Atom,.id它尝试调用该函数id在名为的模块上nil(不存在)。要解决此问题,您可以添加另一个检查来查看是否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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

函数 nil.id/0 未定义或私有 - Elixir 的相关文章

随机推荐