Blog posts for Ruby, Ruby on rails and Linux.

Go back to all blogs

User friendly urls with friendly_id gem in rails 4

Kapil Raj Nakhwa2013-Oct-23
Urls like be machine readable but these links do not make much sense to humans. Friendly id has been a great tool along the life time of rails 3 projects. So I am writing about how to get user friendly urls with the friendly_id gem in rails 4. 
The friendly_id team has set up release candidate for rails 4 ready, But few things have changed from the previous releases of friendly id version 4.
First off we might want to start with adding the release candidate gem in the gemfile 

gem 'friendly_id', '~> 5.0.0'

run bundle install
Extend the friendly id in the model you want to user pretty urls in and define the attribute you want to use as friendly id.

class Products < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
Notice the use: :slugged. It is there to use slugs. Now if you run this code then you are going to get an error about undefined slug.
So add the column called slug into the products model.
rails g migration add_slug_to_products slug:string
Slug is used to store the friendly urls so you might also consider to index them in the database.
Run rake db:migrate
Now time to make all these work. Since version 5 of the friendly_id gem. ActiveRecord finders are not automatically working for use. So one option is to change your finder codes in this format
Or if you can do the folowing.
friendly_id :name, use: [:slugged, :finders]
And that should be it to help you with using pretty urls in your rails 4 application.

Further Resources:

If you guys are new to ruby on rails and are looking for a great way to get you upto the speed . Checkout this awesome udemy's course on ruby on rails .

Tags: friendly_id,rails4,Turbolinks,urls,seo

Go back to all blogs
Never miss a post on new ruby and rails tips