【问题标题】:Display last record in database using Phoenix/Ecto使用 Phoenix/Ecto 显示数据库中的最后一条记录
【发布时间】:2017-05-06 06:41:07
【问题描述】:

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

我有一个名为“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

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

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:
    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)
    

    改为。

    【讨论】:

    • 你是对的。那已经奏效了!如果我创建更多查询,我可以继续将它们添加到该渲染数组中吗?
    • 是的。 render(conn, "index.html", last_radio: last_radio, foo: foo, bar: bar)。您可以根据需要分配任意数量的值。
    • 太好了,谢谢@justinwood。
    • @SimonCooper 此外,您可以使用主键(索引)代替inserted_at 进行排序,例如last_radio = Radio |> last |> Repo.oneEcto.Query.last/2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多