To get search engine friendly urls in my rails application, all I had to do is the following 5 steps:
- Install the acts_as_urlnameable plugin using one of the following command:
script/plugin install http://code.helicoid.net/svn/rails/plugins/acts_as_urlnameable/
or if you’re using svn for your project, install with -x:
script/plugin install -x http://code.helicoid.net/svn/rails/plugins/acts_as_urlnameable/
or alternatively you could use piston.
- Next you need to add the call to acts_as_urlnameable to your model class:
class Advert < ActiveRecord::Base acts_as_urlnameable :title end
- Now we need to add the migration for the urlnames table where we’ll store our new url names:
class Urlnames < ActiveRecord::Migration def self.up create_table :urlnames do |t| t.string :nameable_type t.integer :nameable_id t.string :name t.auto_dates end enddef self.down drop_table :urlnames end end
- Next we need to override the to_param method in the model class, this will allow us to control what rails use in the urls:
def to_param urlname end
- Lastly, we need to update the ActiveRecord.find(params[:id]) calls to use the acts_as_urlnameable find_by_url method:
# GET /adverts/1 # GET /adverts/1.xml def show @advert = Advert.find_by_urlname(params[:id]) respond_to do |format|
And there you have it, friendly urls…
Normally your show url for your model would look as follows (if you’re using RESTfull design)
http://localhost:3000/adverts/1
but now the url looks pretty….
http://localhost:3000/adverts/awesome_macbook_pro_17
There is much more you can do with the acts_as_urlnameable plugin, but I’d suggest you read the README file that does a good job of explaining how to use the plugin.
There are also other plugins you can use for friendly urls, here is a list of other plugins:
Powered by ScribeFire.





