2017-05-03 8 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>

Iは、無線コントローラを、私はページコントローラでクエリを書くべきであると仮定していませんよ?

このすべては、次のコンソールエラーが発生:

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

これはおそらく、サイコーの基本である、と私は非常に単純な何かが欠けてる想像が、何!?

答えて

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

偉大な、ありがとう@ちょうど良い。 –

関連する問題