header image

Code Snippets

Rails Human Friendly Resource URIs

| Last updated:
class BlogPost < ApplicationRecord
  belongs_to :blog

  def to_param
    parameterized_title = "-#{title.parameterize}" if title&.present?
    "#{id}#{parameterized_title}"
  end
end

Create Human Readable URIs for Ruby on Rails Models

Update Model

Overwrite the inherited to_param method with the code snippet to return custom parameters for the model.

Parameterizing the 'title' attribute will remove any non-valid URI characters while keeping it human readable. Alternatively use URI.escape(<attribute>) to keep all characters but have them escaped for URIs.

Adding the unique model id in front of the title will ensure that URIs do not clash.

Notes:

  • Assumes the model has a human-readable attribute named 'title', can be replaced with any other string attribute.
  • Tested in Ruby on Rails v5.2 and v6