2017-04-15 22 views
0

我想要一個從數據庫表中獲取所有條目並返回它們的路由。路由到控制器,從數據庫中獲取並在http響應中返回結果

在router.ex

get "/categories/" do 
    [controller] = ["repo"] 
    Api.Repo.getCategories(conn, controller) 
    end 

在repo.ex:

def getCategories(conn, controller) do 
    conn 
    start_link 
    categories = Api.Category |> all 
    |> put_resp_content_type("application/json") 
    |> send_resp(200, categories) 
    end 

Api.Category.ex

defmodule Api.Category do 
    use Ecto.Schema 

    schema "categories" do 
    field :name, :string 
    end 

    def changeset(category, params \\ %{}) do 
    category 
    |> Ecto.Changeset.cast(params, [:name]) 
    |> Ecto.Changeset.validate_required([:name]) 
    end 
end 

我得到這些警告和錯誤:

warning: variable conn in code block has no effect as it is never returned (remove the variable or a 
ssign it to _ to avoid warnings) 
    lib/api/repo.ex:174 

warning: variable "start_link" does not exist and is being expanded to "start_link()", please use pa 
rentheses to remove the ambiguity or change the variable name 
    lib/api/repo.ex:175 

warning: variable "categories" does not exist and is being expanded to "categories()", please use pa 
rentheses to remove the ambiguity or change the variable name 
    lib/api/repo.ex:178 

warning: variable "controller" is unused 
    lib/api/repo.ex:173 

warning: variable "categories" is unused 
    lib/api/repo.ex:176 


== Compilation error on file lib/api/repo.ex == 
** (CompileError) lib/api/repo.ex:178: undefined function categories/0 
    (stdlib) lists.erl:1338: :lists.foreach/2 
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6 

看起來我正在使用categories。我究竟做錯了什麼?

+0

哦,我的...這是一些很好的代碼質量。 – JustMichael

回答

0

你的錯誤是由

categories = Api.Category |> all 
|> put_resp_content_type("application/json") 
|> send_resp(200, categories) 

這是一個流水線分配給類引起的。因此,未設置send_resp(200, categories)中的類別。

要清楚,這是另一種方式來寫相同的代碼:

categories = 
    Api.Category 
    |> all 
    |> put_resp_content_type("application/json") 
    |> send_resp(200, categories) 

此外,connstart_link是錯誤的。 conn什麼都不做,start_link通常返回一個丟失的PID。

我相信你想是這樣的:

categories = all Api.Category 
    conn 
    |> put_resp_content_type("application/json") 
    |> send_resp(200, categories) 

整個例子看起來很奇怪。我從來沒有看到這種類型的東西在回購模塊。通常,你會在控制器中找到它。我無法評論route.ex文件,因爲我從未創建過類似的路線。

您是否正在關注一個示例?如果是這樣,那是什麼?

+0

謝謝!我已完成[此Ecto入門頁面](https://hexdocs.pm/ecto/getting-started.html)和[本教程介紹Elixir插件路徑入門](https://jarredtrost.com/getting-以elixir-plug-routes-3bbd1dba00e開始),我試圖將它們混合在一起以創建一個API,使前端接口與數據庫連接,以檢索並插入數據庫條目。我確實需要一個控制器,但只是有點失落。我將嘗試將數據庫查詢移動到控制器。我認爲,因爲它是在數據庫Repo上進行操作,它應該在Repo模塊中。 – BeniaminoBaggins

+0

我試圖做的是選擇「類別」數據庫表中的所有條目,並將它們返回到http響應正文中。您的示例是否獲取類別數據庫表中的條目? – BeniaminoBaggins

+0

我得到'回購Api.Repo未啓動,請確保它是您的監督樹的一部分'錯誤 – BeniaminoBaggins

相關問題