How do you use the FriendlyID Gem in Ruby on Rails?
Using a FriendlyID gem enables a user to access a particular resource based on its name rather than its id. For example, imagine the URL www.123abc.com/resources/1. With the FriendlyID gem, a user may be able to access it as www.123abc.com/resources/my-favourite-resource. This operation is known as canonical cleaning or URL, which results in a “FriendlyID is used across most Rails projects due to its ability to make web links memorable. However, it does nothing except provide users with the ability to access a particular resource more conveniently.
The following is the series of steps required for installation and usage:
Step 1
Install the gem:
// this command will install it globally
gem install friendly_id
Step 2
Add a slug column to our desired table:
rails g migration AddSlugToUsers slug:uniq
Step 3
Generate the friendly configuration file and new migration:
rails generate friendly_id
Step 4
Run the migration scripts:
rails db:migrate
Step 5
Edit in the app/models/user.rb file like:
class User < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
end
Edit in the app/controllers/users_controller.rb file and replace User.find by User.friendly.find
class UserController < ApplicationController
def show
@user = User.friendly.find(params[:id])
end
end
Now, you create a new user like the following:
User.create! name: "alex williams"
You can then access the user show page using http://localhost:8000/users/alex-williams.
Free Resources