Pretty URLs with FriendlyId in Rails application

Improve Search Engine Optimization (SEO) with Rails
Luan Nguyen
Apr 10, 2020 · 1 min read

Source: unsplash.com/@merakist

Introduction

FriendlyId is a useful gem that helps you create pretty URLs and work with human-friendly strings as if they were numeric ids. 
Example:
# without FriendlyId 
http://localhost:3000/posts/75 

# with FriendlyId 
http://localhost:3000/posts/pretty-urls-with-friendlyid

How to use

Step 1: Add gem to Gemfile
gem 'friendly_id', '~> 5.3'

Execute:
bundle install

Step 2: Add slug column to Post model
rails generate migration AddSlugToPosts slug:uniq

The migration file look like:
class AddSlugToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :slug, :string
    add_index :posts, :slug, unique: true
  end
end

Don't forget run migration:
rails db:migrate

Step 3: Using friendly_id in Post model
class Post < ActiveRecord::Base
  extend FriendlyId 
  friendly_id :title, use: [:slugged] 
end

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

To re-generate slugs for existing posts, go to console and run:
Post.find_each(&:save)


Finders in FriendlyId

Add :finders option 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])


Generate New Slugs

To re-generate new slugs when you update the title, you have to override the method #should_generate_new_friendly_id? as below:
class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: [:slugged]

  def should_generate_new_friendly_id?
    title_changed? || super
  end
end

References:

Happy Coding with Rails!