0

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.

3 Answers 3

1
resources :questions do
  member: title
end

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.