now available

now available
Want fresh tech tips in your inbox?

Override to_param method in model to get pseudo permalinks without any work


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 w/ #active_record #hacks #permalinks #to_paramruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app