使用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

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

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)

而不是。

最新更新