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

So, I am looking for a solution that will help me achieve the following with the Rails resource:

/admin/articles/:slug/edit 

Unlike

 /admin/articles/:id/edit 

I am looking for Rails resource routes , not other types of routes.

I just wanted to know if this is possible. If so, how?

+5
source share
2 answers
 # config/routes.rb resources :articles, param: :slug 

In terminal:

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

The :id parameter in routing is just a placeholder and can be anything: from a numeric identifier to a bullet.

You just need to pass the correct value

 article_path(id: @article.slug) 

and extract the article using the appropriate method

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

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

 article_path(@article) 

and automatically slug will be assigned to :id .

+6
source

All Articles