Get same url structure as on Stack Overflow

2019-09-05 14:29发布

问题:

A question on SO has this url structure:

http://stackoverflow.com/questions/18474799/changing-the-input-value-in-html5-datalist

If we assume that the number section is the ID, the first two sections (after the domain extension) are obtained by simply using the following in routes.rb

resources :questions

The question is already identified by it's ID, so how do we add the (optional) decorating slug in the simplest of manners? Do we need to use a new link helper (and including additional params) or can the 3-section url be resolved elsewhere?

Update:

To focus this question more on the route-handling, let's presume there is already a slug saved on the object (upon creation) as an attribute, e.g. @question.slug

It would really be an advantage if a rule in routes.rb or/and in the controller could enable and handle the optional slug, instead of having to write long link helpers in all views.

回答1:

resources :questions do
  member: title
end

for slug use friendly_id and yes don't forget to have a look at Rails Routing



回答2:

You might be able to use the to_param method to create a "friendly id".

Something like this:

class Question < ActiveRecord::Base
  def to_param
    [id, name.parameterize].join("/")
  end
end

More info in this gist



回答3:

If you just want to handle the GET requests in that manner, it's easy to do:

get '/questions/:id/:title' => 'questions#show',  as: :question_with_title
resources :questions

This way you can handle incoming URLs with or without the title (just as StackOverflow can -- try it!). You can create urls dynamically with something like:

question_with_title_path(@question.id, @question.title.to_s.downcase.gsub(/ /, '-')
# probably will want to use a method for processing titles into url-friendly format

More at http://guides.rubyonrails.org/routing.html#static-segments