2017-02-16 15 views
0

我有以下控制器:鳳凰插頭檢查所需的查詢參數

defmodule Campaigns.CampaignController do 
    use Campaigns.Web, :controller 

    alias Campaigns.Campaign 
    alias Campaigns.ApiParams 

    plug :ensure_account_id 

    def index(conn, %{"account_id" => account_id}) do 
    query = from c in Campaign, where: [account_id: ^account_id] 
    render(conn, "index.json", campaigns: Repo.all(query)) 
    end 

    def show(conn, %{"id" => id, "account_id" => account_id}) do 
    query = from c in Campaign, where: [id: ^id, account_id: ^account_id] 
    render(conn, "show.json", campaign: Repo.one(query)) 
    end 

    defp ensure_account_id(conn, _) do 
    cs = ApiParams.changeset(%ApiParams{}, conn.params) 
    case cs do 
     %{:params => %{"account_id" => account_id}, :valid? => true} -> 
     conn 
     _ -> 
     conn 
     |> put_status(400) 
     |> render(conn, "400.json", "account_id is missing") 
    end 
    end 
end 

我想確保account_id存在於在這個控制器的每個端點的請求。在我收到控制檯的錯誤是

[error] #PID<0.403.0> running Campaigns.Endpoint terminated 
Server: localhost:4000 (http) 
Request: GET /api/campaigns/1 
** (exit) an exception was raised: 
    ** (FunctionClauseError) no function clause matching in Phoenix.Controller.render/4 

但我有我的ErrorView.ex文件render("400.json"方法。

這裏是我的ErrorView.ex文件

defmodule Campaigns.ErrorView do 
    use Campaigns.Web, :view 

    def render("404.html", _assigns) do 
    "Page not found" 
    end 

    def render("500.html", _assigns) do 
    "Internal server error" 
    end 

    def render("400.json", %{"message" => error}) do 
    %{error: error} 
    end 

    # In case no render clause matches or no 
    # template is found, let's render it as 500 
    def template_not_found(_template, assigns) do 
    render "500.html", assigns 
    end 
end 
+0

'put_status/2'返回'conn'so你必須刪除'conn'在'render'功能 – TheAnh

+0

對不起,我是Phoenix/Elixir的新手,你是什麼意思? – dennismonsewicz

回答

1
defp ensure_account_id(conn, _) do 
cs = ApiParams.changeset(%ApiParams{}, conn.params) 
case cs do 
    %{:params => %{"account_id" => account_id}, :valid? => true} -> 
    conn 
    _ -> 
    conn 
    |> put_status(400) 
    |> render("400.json", message: "account_id is missing") # remove the `conn` here 
end 

+0

啊,好的!當我這樣做時,我收到[錯誤] #PID <0.547.0>運行Campaigns.Endpoint終止的錯誤 服務器:localhost:4000(http) 請求:GET/api/campaigns/1 **(退出)發生異常: **(FunctionClauseError)Phoenix.Controller.render中沒有函數子句匹配/ 3 – dennismonsewicz

+0

已編輯。第三個參數應該是關鍵字或地圖。 – TheAnh

+0

我在原始問題中添加了我的ErrorView,並且改變了我的'render'調用以匹配您擁有的。 – dennismonsewicz