2017-01-02 68 views
0

我試圖檢查user_id對我的elixir函數中的資源ID,但我是新來的語言,知道爲什麼我得到這個錯誤web/controllers/admin/project_controller.ex:12: undefined function resource/0web/controllers/admin/project_controller.ex:12:未定義的函數資源/ 0 - elixir

這裏是我的代碼:

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)值或者是說沒怎麼藥劑工作。我有點困惑。

+2

你從哪裏該行'資源= Guardian.Plug.current_resource(康涅狄格州)&&用戶越來越'resource.id'。 id == resource.id - >'?另外,在'cond'控制結構的這一行中,你不能在這裏綁定/模式匹配。您只能檢查表達式是真/假的條件。 –

+0

將賦值放在括號中應該解決這個問題。我已經更新了我的原始答案,該問題中的代碼來自:http://stackoverflow.com/a/41432647/320615。 – Dogbert

回答

1

像@KeithA在他的評論中說的,你不能匹配你的cond塊的值,所以你得到的原因resource/0未定義是因爲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