Pretty Stack Overflow-style resource URLs in Rails 5

in code


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.



Coffee is Good

in code

Remap a JavaScript Object

in code


Your email address will not be published. Required fields are marked *