【问题标题】:Can't get Phoenix link route to work无法使 Phoenix 链接路由正常工作
【发布时间】:2017-05-04 01:04:13
【问题描述】:

我有一个“收音机”模型,在我的主页(template/page/index.html.eex) 上,我正在提取最后录制的内容。这工作正常,但我正在努力获得工作链接以通过显示页面(template/radio/show.html.eex) 获取该特定记录。

在控制台中我得到:

== Compilation error on file web/controllers/radio_controller.ex ==
** (CompileError) web/controllers/radio_controller.ex:31: undefined function last_radio/0

网上很多例子都使用@conn:

<%= link "Show", to: radio_path(@conn, :show, radio), class: "button" %>

我已经尝试将其更改为我对last_radio 的查询:

<%= link "Show", to: radio_path(@last_radio, :show, radio), class: "button" %>

但这不起作用。

也没有:

<%= link "Show", to: radio_path(@conn, :show, last_radio), class: "button" %>

radio_controller

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

  alias Radios.Radio

  def index(conn, _params) do
    radios = Repo.all(Radio)
    render conn, "index.html"
  end

  def show(conn, %{"id" => id}) do
    radio = Repo.get!(Radio, id)
    render(conn, "show.html", radio: radio)
  end

page_controller

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

  alias Radios.Radio


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

  end
end

我做错了什么?

【问题讨论】:

  • 错误在第 31 行,但是,您提供的代码显示少于 31 行。控制器比那个长吗?
  • 是的,但您在下面的回答已解决。

标签: routes elixir phoenix-framework


【解决方案1】:

如果您想在模板中使用来自控制器的绑定,您需要在它们前面加上 @。因此,对于 templates/radio/ 文件夹中的链接,请使用:

<%= link "Show", to: radio_path(@conn, :show, @radio), class: "button" %>

对于templates/page 使用:

<%= link "Show", to: radio_path(@conn, :show, @last_radio), class: "button" %>

补充说明:

如果您从模板渲染部分,则来自调用模板的绑定不会传递给部分。你需要自己处理它们。我正在添加它,以便将来为您节省一些时间。

<%= render "my_partial", conn: @conn, radio: @radio %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 2016-11-26
    • 2014-12-05
    • 2018-01-17
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多