Stack Overflow uses routes with the format /:id/:title
for questions like this one, which I find to be more memorable than simply a terse ID. I’ve decided that I want this for my new project, a rewrite of this blog in Ruby on Rails 5. Small changes to a model and its routes are required to permit this:
Routes
A post on Stack Overflow led me to a GitHub issue which outlined breaking changes in the to_param object method and a need to glob the route.
get '/ponies/*id', to: 'ponies#show', as: :pony
Model
Add your custom slug:
class Pony < ApplicationRecord
def to_param
"#{id}/#{name.parameterize}"
end
end
And that’s it, simple as.
Ben Sheldon #
This is a really helpful post!
I have since discovered a slightly different way to generate Stack Overflow URLs that has a few benefits:
id
out from the sluggedtitle
resolve
method which can construct even more complicated urls (if necessary)update
anddelete
routes still work by maintainingDELETE ponies/:id
Here’s the method I’m now using:
…which generate these routes:
Mark Grealish #
Ben I edited your comment slightly for formatting. That looks like a pretty awesome solution for the problem! Shows there’s more than way to climb a cliff.