Unlocking SEO-Friendly URLs with FriendlyID Gem

railsMarch 19, 2024Dotby Alkesh Ghorpade

In web development, the significance of Search Engine Optimization (SEO) cannot be overstated. A crucial aspect of SEO is crafting user-friendly and descriptive URLs that aid search engines in understanding your content and enhance the overall user experience. In the Ruby on Rails ecosystem, achieving such URLs can be effortlessly accomplished with the help of the FriendlyID gem.

Introduction

FriendlyID is a Ruby gem that simplifies creating human-readable and SEO-friendly URLs for Rails applications. It achieves this by allowing developers to generate slugs human-readable versions of a resource's title or attribute and use them as part of the URL.

The primary goal of FriendlyID is to replace ugly URLs, typically containing database IDs or complex parameters, with clean and descriptive slugs. For example, instead of having a URL like example.com/posts/123, FriendlyID enables you to have example.com/posts/ruby-on-rails-gem-friendlyid.

Installation

Integrating FriendlyID into your Rails application is straightforward. Add the gem to your Gemfile:

# Gemfile

gem 'friendly_id'

Then, run bundle install to install the gem. Next, generate a migration to add a slug column to your model:

rails generate migration AddSlugToPosts slug:string:uniq

After migrating your database, you can start using FriendlyID in your models:

class Post < ApplicationRecord
  extend FriendlyId
  friendly_id :title, use: :slugged
end

That's it! FriendlyID will now automatically generate slugs based on the :title attribute of your Post model.

Note: When integrating FriendlyID into an existing Rails application, you might need to create slugs for users already in your database. You can achieve this by running the process from the Rails console, using the Rails runner, or setting up a dedicated Rake task.

User.find_each(&:save)

Slug

FriendlyID revolves around the concept of slugs. These are human-readable keywords embedded within URLs that identify a specific page, replacing cryptic numeric IDs. This approach enhances your application's user experience and search engine optimization (SEO).

FriendlyID strives for seamless integration. Text-based identifiers (slugs) can be treated just like standard IDs. This allows you to perform record lookups using slugs like with numeric IDs.

Post.find(1001)
Post.friendly.find("ruby-on-rails-gem-friendlyid")

FriendlyID provides powerful finders that prioritize searching by your custom slug. They seamlessly fall back to searching by the original numeric ID if a match isn't found. This user-friendly approach simplifies integration with existing applications, requiring minimal code changes.

# These queries will work
Post.friendly.find('ruby-on-rails-gem-friendlyid')
Post.friendly.find(1001)
Post.find(1001)

# The below query will not work
Post.find('ruby-on-rails-gem-friendlyid')

Generating Slugs

FriendlyID leverages the parameterize method from Active Support to craft user-friendly slugs. This method cleverly converts spaces into dashes and transforms characters outside the Latin alphabet into their closest ASCII equivalents.

post = Post.create!(title: "Ruby on Rails Gem FriendlyID")

puts post.slug
 => "ruby-on-rails-gem-friendlyid"

Custom method for slug generation

While it might initially seem unusual, FriendlyID generates slugs based on methods, not directly from database columns. This is because Active Record automatically creates methods for accessing each column in your model's table, and FriendlyID utilizes these methods to extract the data it needs for slug creation.

class User < ApplicationRecord
  friendly_id :first_and_last_name

  def first_and_last_name
    "#{first_name}-#{last_name}"
  end
end

user = User.create!(first_name: "Sam", last_name: "Example")
user.friendly_id
 => "sam-example"

Handling Uniqueness

FriendlyID prioritizes URL uniqueness. If a slug conflict arises during record creation, it cleverly appends a UUID to the generated slug, ensuring no two URLs are identical.

user1 = User.create!(first_name: "Sam", last_name: "Example")
user2 = User.create!(first_name: "Sam", last_name: "Example")

user1.friendly_id
 => "sam-example"

user2.friendly_id
 => "sam-example-8b4562bc-b99e-4800-802d-1ad929e177de"

The UUID won't generate user-friendly URLs. The slug_candidates method in the FriendlyID gem is a powerful tool for customizing how your application generates friendly URLs (slugs) for your models.

class Product < ApplicationRecord
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  private

  def slug_candidates
    [
      :name,             # Use just the product name (e.g., "ruby-rails-book")
      [:name, :brand],   # Use name and brand (e.g., "ruby-rails-book-by-pragmatic-programmers")
      [:name, :category] # Use name and category (e.g., "ruby-rails-book-programming")
    ]
  end
end

FriendlyID will first attempt to create a slug using just the name attribute. If a conflict arises (another product already has that slug), FriendlyID will try to combine the name and brand for a more specific slug. Finally, if a unique slug still can't be generated, FriendlyID will attempt a combination of name and category.

By understanding and utilizing the slug_candidates method effectively, you can create a robust and flexible system for generating unique and informative slugs for your models in Rails applications using FriendlyID.

Key Features

  • Automatic Slug Generation

    FriendlyID seamlessly generates slugs based on a specified attribute of the model. Developers can configure which attribute to use, such as :title, :name, or any other relevant field.

    class Post < ApplicationRecord
      extend FriendlyId
      friendly_id :title, use: :slugged
    end
  • Customizing Slugs

    Developers can customize the generated slugs by implementing their logic using callbacks provided by FriendlyID. This enables finer control over slug generation, allowing for scenarios like stripping special characters, converting to lowercase, or incorporating additional data into the slug.

    class Post < ApplicationRecord
      extend FriendlyId
      friendly_id :custom_slug, use: :slugged
    
      def custom_slug
        # Custom logic to generate slug
      end
    end
  • Scoped Slugs

    FriendlyID supports scoping slugs within a specific context. This is particularly useful when dealing with models with associations or belonging to a specific category. Scoped slugs ensure uniqueness within the defined scope.

    class Article < ApplicationRecord
      extend FriendlyId
      friendly_id :title, use: [:slugged, :scoped], scope: :category
    end
  • History Tracking

    By default, FriendlyID keeps track of slug changes over time, ensuring that old URLs remain functional even after a slug has been updated. This prevents broken links and maintains the integrity of your website's SEO.

  • SEO Optimization

    FriendlyID enhances the SEO of your Rails application by creating URLs that are not only more readable to users but also more favourable to search engines. By incorporating relevant keywords into the slug, you can improve the ranking of your pages in search results.

Best Practices

While FriendlyID simplifies the process of creating SEO-friendly URLs, it's essential to follow some best practices to maximize its effectiveness:

  • Choose Relevant Attributes

    Select attributes that best represent the content and are relevant for generating slugs. Typically, titles or names work well but consider your specific use case.

  • Keep Slugs Concise

    Aim for slugs that are concise, descriptive, and easy to read. Avoid stuffing keywords or unnecessary information into the slug.

  • Handle Duplication

    Implement logic to handle slug duplication, especially if your application allows multiple resources with similar titles. FriendlyID provides options for handling conflicts, such as appending a sequence or timestamp.

  • Test thoroughly

    Test your FriendlyID implementation thoroughly, especially if working with existing data. Ensure that slugs are generated correctly and that old URLs redirect to the new ones seamlessly.

Conclusion

Optimizing your website for search engines is paramount in the competitive landscape of the internet. FriendlyID empowers Ruby on Rails developers to create clean, user-friendly URLs that enhance both SEO and user experience. By automating the process of generating slugs and providing flexibility for customization, FriendlyID simplifies the task of crafting SEO-friendly URLs, enabling you to focus on building great content and engaging user experiences. Whether you're building a blog, e-commerce platform, or any other web application, consider integrating FriendlyID to unlock the full potential of your URLs.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at [email protected] or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right