Written by Sean Behan on Sun Jun 17th 2012

There are a number of permalink plugins for Rails, http://www.seoonrails.com/even-better-looking-urls-with-permalink_fu, is a good one that I've used before. However, this involves informing the model class (has_permalink :title), adding a route, using the route in your views and controllers and of course running some migrations. If you're willing to get 99% of the functionality for 0% of the work, just override the to_param method in your model.

This assumes you have an attribute for your model that you'd like to use for your permalink, but that's it.


class Post < ActiveRecord::Base
  def to_param
    "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-').downcase}"

That's it. You don't have to change your controllers, routes or views. Your URL will look something like

Active record will strip all alpha characters from the params[:id] variable leaving you with just the integer value of your model.

So long as you don't mind that integer in the url, it's an easy solution that you can bake in at any point w/out having to touch the rest of your application code.

Tagged with..
#active_record #hacks #permalinks #to_param #Ruby on Rails

Just finishing up brewing up some fresh ground comments...