Stack Overflow-like URL routes in rails 3

2019-04-13 14:55发布

问题:

So I want my app to generate routes like stack overflow

questions/:id/:title

How can I do this in rails?

回答1:

Please note that:

http://stackoverflow.com/questions/4434266/stack-overflow-like-url-routes-in-rails-3

http://stackoverflow.com/questions/4434266/

http://stackoverflow.com/questions/4434266/you-can-put-wathever-you-want-here

Are the same. I guess stackoverflow just does that in order to provide some context if you see just the link there.

So, your route would be just this one:

http://stackoverflow.com/questions/4434266/

which should be something like:

http://stackoverflow.com/questions/:id

You can ignore the rest of the url



回答2:

This is what I was looking for:

http://norman.github.com/friendly_id/file.Guide.html

hope this can help others!



回答3:

Everything you could ever want to know about routes: http://guides.rubyonrails.org/routing.html

Take a look specifically at http://guides.rubyonrails.org/routing.html#static-segments. What you want to do is create a route that maps to the controller and passes the question id and title as paramaters. Then your controller action will grab that information and render the correct view. The title attribute has to be accessible in your controller, it can't be only accessible in your view.