Ruby on Rails: Use slug instead of id on resource routes

做~自己de王妃 提交于 2019-12-22 03:58:34

问题


So I'm looking for a solution that would help me achieve the following with Rails resource:

/admin/articles/:slug/edit

as opposed to

/admin/articles/:id/edit

I'm looking for Rails resource routes and not the other kinds of routes.

Just wanted to know if it was possible. If so, how?


回答1:


# config/routes.rb
resources :articles, param: :slug

In the terminal:

$ rake routes
...
article GET    /articles/:slug(.:format)      articles#show
...



回答2:


The :id parameter in the routing is simply a placeholder and can be anything, from a numeric identifier to a slug.

You just need to pass the proper value

article_path(id: @article.slug)

and fetch the article using the appropriate method

Article.find_by!(slug: params[:id])

If you prefer, you can also override the to_param for the Article model to return the slug, so that you can use

article_path(@article)

and automatically the slug will be assigned to the :id parameter.



来源:https://stackoverflow.com/questions/31059992/ruby-on-rails-use-slug-instead-of-id-on-resource-routes

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