Read more

Slugs with FriendlyId

Tobias Kraze
August 25, 2010Software engineer at makandra GmbH

Gem to provide nice looking urls ("/blog/the-greatest-bug-i-never-fixed"). If you don't need anything too special (like i18n for the urls) it works as a drop-in-replacement. It basically overwrites #to_param to return the slug, and .find to search by the slug.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Make sure, everywhere you build paths, you use model_path(:id => model) instead of model_path(:id => model.id). You also need to adapt all code using something like .find_by_id. The regular .find is fine.

See the github README for installation instructions.

Don't forget to give your model an indexed string column named cached_slug. A sane configuration seems to be

class Model
  has_friendly_id :title, :use_slug => true, :approximate_ascii => true, :ascii_approximation_options => :german, :strip_non_ascii => true
end

Then :german option converts "ΓΌ" to "ue" etc.

To build initial slugs, use the provided rake task

rake friendly_id:redo_slugs MODEL=MyModel

If slugs change over time, FriendlyId remembers the old slugs, so .find still works (only with the :use_slug => true option). You should however always redirect to the current version of the slug in your view. For this, do something like the following, possibly in a before_filter

unless @record.friendly_id_status.best?
  redirect_to :id => @record
end

Also so see the excellent guide Show archive.org snapshot .

Posted by Tobias Kraze to makandra dev (2010-08-25 10:24)