Ruby on Rails: Use slug instead of id on resource

2019-04-22 12:10发布

问题:

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.