使用 Phoenix/Ecto 显示数据库中的最后一条记录

Display last record in database using Phoenix/Ecto

这是一个非常基本的问题,我无法在网上找到详细信息。

我有一个名为 'Radios' 的型号,我希望显示添加到我主页的最后一个收音机 - 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

这可能太基础了,想象一下我错过了一些非常简单的东西,但是什么!?

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)

相反。