在phoenix框架(elixir)中更改URL以接受字符串而不是id [英] Change Url to accept a string instead id in phoenix framework (elixir)
问题描述
我正在尝试在phoenix应用程序中实现永久链接.
I am trying to implement permalinks in phoenix app.
目标是将localhost:4000/products/1更改为localhost:4000/products/productname
The goal is to change localhost:4000/products/1 to localhost:4000/products/productname
我尝试在永久链接在Rails中的实现中跟随Ryan Bates剧集 但无法在phoenix中为模型找到to_param函数.
I tried following Ryan Bates episode on permalinks implementation in rails but wasn't able to find a to_param function for models in phoenix.
请帮助.
推荐答案
不确定这是否是您要的东西,但是您去了:
Not sure if this is what you are asking for but here you go:
router.ex在浏览器堆栈中
router.ex in the browser stack
get "/products/:product_name", ProductController, :get_product_by_name
product_controller.ex
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
如果您希望您的应用程序将基于名称的特定产品作为html页面返回,这应该就是您所需要的,自然地,您将需要在template/product下有一个名为"product_info.html.eex"的html页面
That should be all you need if you want your application to return a specific product based on name as a html page, naturally you will need to have a html page with the name "product_info.html.eex" under templates/product
这篇关于在phoenix框架(elixir)中更改URL以接受字符串而不是id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!