Create Friendly URLs With FriendlyId

This article will show you how to create nicer urls for your rails applications using the FriendlyId Gem.


Published on:October 12, 2012
Note:  This article applies to FriendlyId 4.x and earlier. For Rails 4, please visit this page.

This article will show you how to create nicer urls for your rails applications using the FriendlyId Gem. This article will only go over the basics of using FriendlyId. A future article will cover more advanced options.

Introducing FriendlyId

FriendlyId allows you to turn generic looking urls into fun, easy to read, SEO friendly URLs. For example:

http://richonrails.com/posts/creating-a-custom-blog-style-url

instead of:

http://richonrails.com/posts/2340783

Installation

To use FriendlyId, you will need to include it in your gemfile.

gem 'friendly_id'

After including FriendlyId, be sure to run the bundle command:

bundle

We are all set and ready to begin using FriendlyId.

Usage in a New Model

Incorporating FriendlyId into a new model is simple. First, we generate the model. We will create a special field called a slug to store the friendly URL.

rails g model Post title:string slug:string body:text

Next, we will need to open up the migration file that was generated and add some code to create an index for the slug:

add_index :posts, :slug, unique: true

Next, we will need to tell rails that we wish to use FriendlyId for our model. Open the model we just created and add the following code:


extend FriendlyId
friendly_id :title, use: :slugged
Advertisement

That's it! Our app will now use FriendlyId. If you add a link in your views, you will notice the new friendly url.

Existing Applications

In order to add FriendlyId to an existing application, we will need to create a migration to add the necessary field to the model we want to use FriendlyId with.

rails g migration AddSlugToPosts

Inside the migration, add the following lines of code:


add_column :posts, :slug, :string
add_index :posts, :slug, unique: true

Next, we will run a db:migrate to update our database:

rake db:migrate

Now, we need to add code to our model to tell rails that we wish to use FriendlyId. Open the desired model and add the following code.


extend FriendlyId
friendly_id :title, use: :slugged

We are almost there! While technically we are all set up and good to go, existing data still doesn't have a slug. In order to add a slug, start a rails console:

rails c

Inside the rails console, run a command to loop through each model and save it:

Posts.find_each(&:save)

This will update our existing records and add slugs for each of them. Exit out of the console by typing:

exit

That's it! We are all finished. Your application should now automatically use the FriendlyId scheme for urls.