更改 Url 以在 phoenix 框架 (elixir) 中接受一个字符串而不是 id

Change Url to accept a string instead id in phoenix framework (elixir)

我正在尝试在 phoenix 应用程序中实现永久链接。

目标是把localhost:4000/products/1改成localhost:4000/products/productname

我试过 permalinks implementation in rails 上的 Ryan Bates 插曲 但无法在 phoenix 中找到模型的 to_param 函数。

请帮忙。

不确定这是否是您要的,但您可以:

router.ex 在浏览器栈中

get "/products/:product_name", ProductController, :get_product_by_name

product_controller.ex

def get_product_by_name(conn, %{"product_name" => product_name}) do
  product = Repo.get_by(Product, name: product_name)
  render(conn, "product_info.html", product)
end

如果您希望您的应用程序 return 基于名称的特定产品作为 html 页面,这应该是您所需要的,自然您需要有一个 html 页面templates/product

下的名字 "product_info.html.eex"

除了 Wobbley 的响应之外,to_param 在 Phoenix 中是通过协议实现的。例如,您可以通过以下方式更改产品 URL 的生成方式:

defimpl Phoenix.Param, for: MyApp.Product do
  def to_param(%{name: name}) do
    "#{name}"
  end
end

Programming Phoenix 上还显示了一个更复杂的示例(免责声明:我是作者之一)。