【问题标题】:web/controllers/admin/project_controller.ex:12: undefined function resource/0 - elixirweb/controllers/admin/project_controller.ex:12: 未定义的函数资源/0 - 长生不老药
【发布时间】:2017-02-26 07:29:36
【问题描述】:

我正在尝试根据我的 elixir 函数中的资源 ID 检查 user_id,但我是该语言的新手,我不知道为什么会收到此错误 web/controllers/admin/project_controller.ex:12: undefined function resource/0

这是我的代码:

def index(conn, %{"user_id" => user_id}) do
    user = Repo.get(User, user_id)
           |> Repo.preload(:projects)
    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
  end

我是否真的将资源设置为 Guardian.Plug.current_resource(conn) 的值,或者这不是 Elixir 的工作方式。我有点困惑。

【问题讨论】:

  • 你从哪里得到resource.id 从这行resource = Guardian.Plug.current_resource(conn) && user.id == resource.id ->?此外,在cond 控制结构的这一行中,您不能在此处绑定/模式匹配。您只能检查表达式为真/假的条件。
  • 将赋值放在括号中应该可以解决这个问题。我已经更新了问题中的代码来自的原始答案:stackoverflow.com/a/41432647/320615

标签: elixir phoenix-framework


【解决方案1】:

就像@KeithA 在他的评论中所说,你不能匹配你的cond 块中的值,所以你得到resource/0 undefined 的原因是因为resource = ... 不起作用。

因此,为了使您的代码正常工作,您可以执行以下操作:

def index(conn, %{"user_id" => user_id}) do
    user = Repo.get(User, user_id)
           |> Repo.preload(:projects)
    resource = Guardian.Plug.current_resource(conn)

    cond do
      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
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2016-02-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 2017-10-21
    相关资源
    最近更新 更多