Slugs with FriendlyId

Updated . Posted . Visible to the public.

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.

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 .

Tobias Kraze
Last edit
Keywords
seo, friendly_id
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2010-08-25 08:24)