2017-05-03 52 views
2

這是一個基本問題,我無法在網上找到詳細信息。使用Phoenix/Ecto顯示數據庫中的最新記錄

我有一個叫做「無線電」模式,我希望顯示的最後一次無線電添加到我的主頁 - templates/page/index.html.eex

我到目前爲止有:

radio.ex

defmodule Radios.Radio do 
    use Radios.Web, :model 
    import Ecto.Query 

    schema "radios" do 
    field :name, :string 
    field :desc, :string 
    field :price, :integer 
    field :text1, :string 
    field :text2, :string 
    field :text3, :string 
    field :text4, :string 
    field :mainimg, :string 

    timestamps() 
    end 

    @doc """ 
    Builds a changeset based on the `struct` and `params`. 
    """ 
    def changeset(struct, params \\ %{}) do 
    struct 
    |> cast(params, [:name, :desc, :price, :text1, :text2, :text3, :text4, :mainimg]) 
    |> validate_required([:name, :desc, :price, :text1, :text2, :mainimg]) 
    end 

    def sorted(query) do 
    from r in query, 
    order_by: [desc: r.inserted_at] 
    end 

end 

page_controller.ex

defmodule Radios.PageController do 
    use Radios.Web, :controller 

    alias Radios.Radio 


    def index(conn, _params) do 
    last_radio = Radio 
    |> Radio.sorted 
    |> Radios.Repo.one 
    render(conn, "index.html", radio: radio) 

    end 
end 

頁面模板

<p class="title is-4"><%= @last_radio.name %></p>

我假設我應該寫在頁面控制器的查詢,而不是無線電控制器?

所有這一切都將導致以下控制檯錯誤:

== Compilation error on file web/controllers/page_controller.ex == 
** (CompileError) web/controllers/page_controller.ex:11: undefined function radio/0 

這可能是SOOOO基礎,並想象我失去了一些東西很簡單,但什麼!?

回答

5
def index(conn, _params) do 
    last_radio = Radio 
    |> Radio.sorted 
    |> Radios.Repo.one 
    render(conn, "index.html", radio: radio) 
end 

要指定查詢的結果last_radio,但你要使用的變量radio當您在渲染分配給它。我相信你會想

render(conn, "index.html", last_radio: last_radio) 

改爲。

+0

你是對的。這一直奏效!如果我創建更多的查詢,我可以繼續將它們添加到該渲染數組中嗎? –

+1

是的。 'render(conn,「index.html」,last_radio:last_radio,foo:foo,bar:bar)''。您可以根據需要分配儘可能多的值。 –

+0

太棒了,謝謝@justinwood。 –

相關問題