Pretty URLs with FriendlyId Gem in Rails

1. Overview

FriendlyId is an add-on to Ruby's Active Record that allows you to replace ids in your URLs with strings:

# without FriendlyId
http://localhost:3000/posts/75

# with FriendlyId
http://localhost:3000/posts/instagram-api-with-rails

2. How to use

Step 1: Add gem

gem 'friendly_id', '~> 5.1.0'


Step2: Add to Post.rb model

class Post < ActiveRecord::Base
  attr_accessible :content, :title

  extend FriendlyId
  friendly_id :title, use: [:slugged]
end

Step 3: Add slug colum to Post

rails generate migration AddSlugToPosts slug:string
rake db:migrate 

The migration file:

class AddSlugToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :slug, :string
    add_index  :posts, :slug
  end
end

 

Step 4: Using

post = Post.friendly.find(params[:id]) 

To generate slugs for existing posts, go to console and run:

Post.find_each(&:save)

3. Finders in FriendlyId

Add options :finders to config in Post model:

friendly_id :title, use: [:slugged, :finders]

Using

#before add :finders
post = Post.friendly.find(params[:id])

#after add :finders 
post = Post.find(params[:id])

4. Generate New Slugs

To re-generate new slugs when you update title, you have to override the #should_generate_new_friendly_id? method as below:

class Post < ActiveRecord::Base
  attr_accessible :content, :title

  extend FriendlyId
  friendly_id :title, use: [:slugged]

  def should_generate_new_friendly_id?
    title_changed? || super
  end
end

Have fun !!!