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

泪湿孤枕 提交于 2019-11-27 23:53:59

问题


I am trying to implement permalinks in phoenix app.

The goal is to change localhost:4000/products/1 to localhost:4000/products/productname

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.

Please help.


回答1:


Not sure if this is what you are asking for but here you go:

router.ex in the browser stack

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

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




回答2:


In addition to Wobbley's response, to_param in Phoenix is implemented with protocols. For example, here is how you could change how the URLs for products are generated:

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

A more complex example is also shown on Programming Phoenix (disclaimer: I am one of the authors).



来源:https://stackoverflow.com/questions/34570612/change-url-to-accept-a-string-instead-id-in-phoenix-framework-elixir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!