VocabReminder
Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

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.

app/models/post.rb


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

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


/posts/45-pseudo-permalinks-with-rails
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