【发布时间】:2018-02-11 04:06:47
【问题描述】:
我是 Elixir/Phoenix 的新手,我想创建一个不使用模型 ID 但最终出现错误的链接:
protocol Enumerable not implemented for %XX.YY.Article{__meta__: #Ecto.Schema.Metadata<:built, "articles">, content: nil, id: nil, inserted_at: nil, short_title: "lalalilala", slug: 457, title: nil, updated_at: nil}.
这是我尝试创建链接的方式:
def link_to_article(conn, article_map) do
article = struct(%XX.YY.Article{}, article_map)
link article_map.short_title,
to: page_path(conn, :index, article),
class: "btn btn-default"
end
我有这个 to_param 的实现:
defimpl Phoenix.Param, for: XX.YY.Article do
alias XX.YY.Slug
def to_param(%{slug: slug, title: title}) do
"#{Slug.pad_slug(slug)}-#{Slug.slugify_title(title)}"
end
end
如果我将article_map 提供给链接,则链接有效,但很难看(地图成为查询字符串)。 article 强制使用 to_param 并创建漂亮的 URL 缺少什么?
编辑,这里是路由器声明:
get "/", PageController, :index
get "/:article", PageController, :index
因为我希望 URL 类似于 qweqwe.com/padded_slug-article_title
在控制器中,我将索引定义为:
def index(conn, %{"article" => article_identifier}) do
[slug|_] = article_identifier |> String.split("-")
article = XX.YY.get_current_article(slug)
case article do
nil -> Phoenix.Controller.redirect(conn, to: "/")
article ->
render conn, "index.html",
articles: XX.YY.get_articles_for_menu!(),
current_article: article
end
end
def index(conn, _params) do
render conn, "index.html",
articles: XX.YY.get_articles_for_menu!(),
current_article: XX.YY.get_default_article!()
end
这段代码丑吗?
到目前为止的所有路线:
page_path GET / QQ.PageController :index
user_path GET /users QQ.UserController :index
user_path GET /users/:id/edit QQ.UserController :edit
user_path GET /users/new QQ.UserController :new
user_path GET /users/:id QQ.UserController :show
user_path POST /users QQ.UserController :create
user_path PATCH /users/:id QQ.UserController :update
PUT /users/:id QQ.UserController :update
user_path DELETE /users/:id QQ.UserController :delete
article_path GET /articles QQ.ArticleController :index
article_path GET /articles/:id/edit QQ.ArticleController :edit
article_path GET /articles/new QQ.ArticleController :new
article_path GET /articles/:id QQ.ArticleController :show
article_path POST /articles QQ.ArticleController :create
article_path PATCH /articles/:id QQ.ArticleController :update
PUT /articles/:id QQ.ArticleController :update
article_path DELETE /articles/:id QQ.ArticleController :delete
page_path GET /:article QQ.PageController :index
调用栈:
(elixir) lib/enum.ex:1: Enumerable.impl_for!/1
(elixir) lib/enum.ex:116: Enumerable.reduce/3
(elixir) lib/enum.ex:1823: Enum.reduce/3
(XX) lib/QQ/router.ex:1: QQ.Router.Helpers.segments/3
(XX) lib/QQ/router.ex:1: QQ.Router.Helpers.page_path/3
(XX) lib/QQ/views/layout_view.ex:8: QQ.LayoutView.link_to_article/2
【问题讨论】:
-
通常
index路径不需要对象 id 或任何对象相关数据,因此最后一个参数只是一个映射或 URL 参数的关键字列表,但这是我的疯狂猜测,用 @ 测试它987654333@ 或edit路径。 -
你能发布你的
router.ex吗? -
@Dogbert 请看我的编辑!
-
@JustMichael 这是因为我不希望 URL 中包含
show。我将生成的资源保留用于管理目的,并使用自定义路由进行查看。 -
@Sautieh 你的
router.ex中是否有另一条路线指向PageController.index?你能发布mix phoenix.routes的输出吗?