Thoughts on Technology, Methodology and Programming.

Friendly url’s in my rails application within minutes

Posted by Marcus Wyatt on 3 November 2007

To get search engine friendly urls in my rails application, all I had to do is the following 5 steps:

  1. 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.

  2. Next you need to add the call to acts_as_urlnameable to your model class:
    class Advert < ActiveRecord::Base
    acts_as_urlnameable :title
  3. 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
    enddef self.down
    drop_table :urlnames
  4. 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
  5. 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)


but now the url looks pretty….


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.


One Response to “Friendly url’s in my rails application within minutes”

  1. Amolimac said

    thanks, Its working.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: