DEV Community

Cover image for Implementing Custom Slugs with FriendlyID in Rails: A Step-by-Step Technical Guide
Nemwel Boniface
Nemwel Boniface

Posted on • Updated on

Implementing Custom Slugs with FriendlyID in Rails: A Step-by-Step Technical Guide

Introduction:

Have you ever wondered how applications like Instagram or Twitter use your username as the unique identifier in your browser URL and not the ID of your account?

In the development of applications, the use of eg usernames instead of the ID is called slugging. In programming, slugs are the human readable unique identifying parts of a web address typically at the end of the URL (Uniform Resource Locator).

Using custom slugs for our applications offers many advantages that I will discuss later in the article. Implementing them in our applications is relatively easy and luckily for us who use Ruby on Rails, we get the advantages of using a mature stable framework where many functionalities have solutions that were already implemented for us.

In Ruby on Rails, we have a gem called friendly_id that makes the process of generating human-readable slugs simple by allowing us to replace ids in our URLs with slugs. Using friendly_id gem lets our applications work with friendly URLs eg https://www.my_app/users/nemwelboniface instead of https://www.my_app/users/1.

Typically, the implementation of custom slugs in Rails involves leveraging gems like FriendlyID that streamline the process and offer additional functionalities like resolving slug conflicts and automatically generating easily readable slugs.

Within this article, we shall delve into a comprehensive step-by-step walk through that demonstrates how to implement custom slugs in Rails with the assistance of the FriendlyID gem. My guide will encompass essential aspects such as installation, configuration, migration, and code generation, enabling a seamless integration of custom slugs into your Rails application. By the conclusion of this tutorial, you will possess the necessary knowledge and tools to craft personalized and user-friendly URLs tailored to meet your specific needs.

Let's dive in and unlock the power of custom slugs in Rails!

Prerequisites:

  1. Rails V7
  2. PostgreSQL database
  3. Ruby V 3+
  4. Visual studio code
  5. Some experience with Rails MVC architecture.

Project set-Up

Cat setting up friendly_id for custom slugs in the project

To set up the custom slugs functionality in our application, we need to add the friendly_id gem to our Gemfile and run bundle install.

gem "friendly_id"
bundle install
Enter fullscreen mode Exit fullscreen mode

If you would like to follow along, I created a new branch called friendly_id in this repository where you can follow along with me. If you would like to know how to create a new Rails application, kindly have a look at the first part of this article I wrote.

Our next step will involve adding a slug column to our desired table. In our case, it will be the Users table. Therefore we shall run the following line in our terminal which will create a migration file that adds a slug column to our Users table.

rails g migration AddSlugToUsers slug:uniq
Enter fullscreen mode Exit fullscreen mode

We shall also need to generate the friendly configuration file and a new migration with the following command:

rails generate friendly_id
Enter fullscreen mode Exit fullscreen mode

We are now free to run the migrations to update the schema file with the new columns added by the migration files created.

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

We are going to head over to our Users model inside app/models/user.rb file and add the following:

class User < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged
end
Enter fullscreen mode Exit fullscreen mode

With the line for "extend FriendlyId" we are extending the functionalities of the User model with the methods that are provided by the FriendlyId module. This is what allows us to use the "friendly_id" method in the next line.

With the line "friendly_id :name, use: :slugged" this is the line that configures the friendly_id gem for the user model. This is where we specify that the name attribute of the user model should be used as the basis for generating the slugs. The :slugged option indicates that the friendly_id gem should use the slugged module to generate the slug.

Making use of the above means that when a new user record is being created, the friendly_id gem will generate a slug based on the name attribute. The slug is then stored inside the slug column in our user's table.

In addition to the above, let us head back to our user's model inside app/models/user.rb file and create a to_param method. Our User model shall now be like this with all the changes made:

class User < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged

  def to_param
    slug
  end
end
Enter fullscreen mode Exit fullscreen mode

This method is necessary when using the friendly_id gem to ensure that our slug is used in the URL instead of the default ID. What it does is overrides the default behavior of Rails when generating URL's for model instances.

By defining the to_param method and returning the slug value, you are instructing Rails to use the slug attribute when generating the URL's for instances of our model.

We are almost done now. We need to make some slight adjustments to our controllers. Head over to our users controller in app/controllers/users_controller.rb file and inside the show action and set_user method, replace this:

@user = User.find(params[:id])
Enter fullscreen mode Exit fullscreen mode

with:

@user = User.friendly.find(params[:id])
Enter fullscreen mode Exit fullscreen mode

What is happening here is we are using the friendly_id gem to find a user's record based on its slug. The params[:id] value is passed in as the argument to the find method. Basically using the friendly.find, the user record will be found based on its slug attribute instead of the ID which is the default behavior of ActiveRecord.

The last step involves running the following in our Rails console:

User.find_each(&:save)
Enter fullscreen mode Exit fullscreen mode

Note to when you need to run the line above

Note that running the above line is only necessary if you're adding friendly_id to an already existing Rails application and you need to generate slugs for already existing users.

What that line does is it iterates over each user's record and calls the save method on them. This triggers the saving process and generation of slugs for each user based on the friendly_id configuration in our user model.

This step is not necessary if you setup friendly_id before creating users in your application. If you find having to run the line in your console application tedius, you have an option of creating a rake task that can be used to automate that process for you. However, this is beyond the scope of what we were to learn in this article. I will however consider writing an article about rake tasks upon request from someone in the comments section.

That's all you need to create custom slugs!

Pros and cons of using custom slugs

We have covered the technical setup and I believe that so far you have an idea of why having custom slugs in your application is a good thing. Below I will list a few advantages that I have found from using custom slugs in my own applications:

  1. It has helped me to improve the SEO of my applications ten fold as search engines tend to give more weight to keywords in the URL when determining the relevance of a page.
  2. Using custom slugs gives you a human readable URL that gives more context and describes what thet specific webpage you are viewing contains. This rings true especially when creating blogs where you can have th title of a blog as the slug for a blogs show page.
  3. Using custom slugs has given my applications alot of flexibility as the slugs are more flexible and meaningful than numeric ID's. Having keywords in the slugs has really helped users of my applications to identify and remember the contents of webpages that they visited from my application.
  4. Persistence and a sense of security in my application as unline numerical IDs are sequential and predictable by revealing th order in which records were created, having the custom slugs give me a sense of security as they remain consistent even if the record is moved or re-ordered in the database.

Despite using slugs showing real tangible benefits to our applications, they also have some serious considerations which are worth factoring when using custom slugs over the default ID's. You need to ensure that the slugs are unique, they can handle situations where the title or the attribute that is used for the slug is changed and also properly handling URL redirections when slugs are modified.

Luckily for us, in Rails all the above concerns are already handled by the friendly_id gem where the process of handling these edge case is simplified. This is one of the many advantages we get from using a mature and stable framework like Ruby on Rails for development of our applications.

Conclusion

Would you like to use friendly_id in your applications after reading my short article? Please let me know in the comments section below.

This one marks the end of the Step-by-Step Guide: Implementing Custom Slugs with FriendlyId in Rails article guide.

That is it for today's class. I hope this was useful information for you. See you in my next article.

Top comments (2)

Collapse
 
ahangarha profile image
Mostafa Ahangarha

Thanks for sharing your experience with this gem. I never heard of it.

I am wondering if implementing slug using an additional filed in the db and customizing routes wouldn't be easier. If I'm not wrong, WordPress stores slug along with other properties of a post in the db.

Any thought?

Collapse
 
nemwelboniface profile image
Nemwel Boniface • Edited

Hello @ahangarha! Thank you for taking the time to read my article and I am happy that you learned something new today!

You are absolutely right that there is an alternative approach to implementing slugs by using an additional field in the database and customizing routes. In fact, in WordPress, the slug is stored separately in the database.

Opting for this approach brings certain advantages as it provides more flexibility in managing and manipulating slugs. They can be easily updated or modified independently from other properties of the post or record.

However, utilizing pre-built solutions like FriendlyId offers a streamlined and efficient solution. It comes with built-in functionality for generating and managing slugs, abstracting away many of the implementation details. FriendlyId provides features such as automatic slug generation, handling slug conflicts, and managing URL redirections when slugs are modified. This can greatly save development time and effort, particularly for complex applications.

All in all I believe the choice of implementing slugs manually or using pre-built solution lies on the developer or the project being worked on.