Rails: How to create Stackoverflow-style URLs using Rails' built-in "resources"?

Stackoverflow URLs are similar to the following:

http://stackoverflow.com/users/12345/name-of-user 

It has all the attributes of a true RESTful route:

 :resource_name/:resource_id 

But it also has a name part after the segment :resource_id . I know how to achieve it using non-wired Rails routes. But is it possible to achieve the same URLs using the default resources :user built-in methods?

By default, the third segment is a format in Rails:

 /users/:id(.:format) users#show 
+4
source share
3 answers

You can use FriendlyId. there is repository on Github and is well documented. Ryan Bates also does very good video tutorials about this at RailsCasts.

0
source

Say you have a questions_controller controller.

In routes.rb:

 get 'questions/:id/:slug', to: 'questions#show' 

In questions_controller.rb:

 def show @question = Question.find(params[:id]) if request.path != question_path(@question) redirect_to @question, status: :moved_permanently return end ... end 

In the .rb question:

 def to_param "#{id}/#{name.parameterize}" end 

What is it. All generated paths will include slug, and if you try to access /questions/42 or /questions/42/incorrect-slug , you will be redirected.

0
source

I know this is an old question, but there still seem to be some interests. Therefore, I will publish what I came up with.

I'm not sure how much you want to be resourceful, but this, with a sip, works:

 resources :articles do member do get '*slug', to: 'articles#show', as: 'slugged' end end 

This also works:

 resources :articles do member do get ':slug', to: 'articles#show', as: 'slugged' end end 

In both cases, you can use

  <%= link_to slugged_article_path(article, article.title.parameterize) %> 

in your views (you can define a virtual attribute in your model for slug, instead of dynamically creating it using article.title.parameterize in the view).

Note that so far, Rails will not complain if you type anything as a bullet in your browser.

I personally find the resourceful approach a bit detailed, since I am only interested in having pretty URLs for show actions (which are the only ones that ordinary users or search engine bots can see), so I find it simpler than that:

 resources :articles get 'articles/:id/:slug', to: 'articles#show', as: 'slugged_article' 
0
source

Source: https://habr.com/ru/post/1482879/


All Articles