ruby

How Can You Transform Boring URLs Into Memorable Links in Your Rails App

Transform Your Rails App's URLs with the Magic of FriendlyId's User-Friendly Slugs

How Can You Transform Boring URLs Into Memorable Links in Your Rails App

When you’re trying to develop user-friendly URLs for your Ruby on Rails app, using the FriendlyId gem is like striking gold. This gem helps you ditch those boring numeric IDs in your URLs in favor of slick, user-friendly slugs that folks can actually read and remember.

First thing’s first, you need to incorporate FriendlyId into your Rails project, and the process is super straightforward.

To start, just add the gem to your Gemfile with:

gem 'friendly_id', '~> 5.2'

You want to ensure you’re using version 5.0.0 or greater, especially if you’re on Rails 4.0 or later.

Then, install it via:

bundle install

Once that’s handled, generate the initializer with:

rails generate friendly_id

This command will create an initializer file in config/initializers, where you can globally fiddle with FriendlyId settings.

Next, you need to add a slug column to your model. So, if you’ve got a User model, you’d run:

rails g migration add_slug_to_users slug:string:uniq
rails db:migrate

This neat little migration adds a unique slug column to your users table.

Okay, gem installed and columns added. Now let’s configure your model.

Extend your model with:

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

With this code, you’re telling FriendlyId to generate a slug based on the name attribute. If there are slugs with the same name, it appends a UUID to keep things unique.

If you’re tacking FriendlyId onto an existing application, don’t forget to generate slugs for your current records:

User.find_each(&:save)

Pretty nifty, huh? This iterates over each user record and saves it, triggering those slugs to be crafted.

Now, let’s use these friendly URLs in your controllers. Just update the find method to use friendly.find instead.

So, for your controller actions, you would tweak them like this:

class UsersController < ApplicationController
  def show
    @user = User.friendly.find(params[:id])
  end

  private

  def set_user
    @user = User.friendly.find(params[:id])
  end
end

This ensures the user record is fetched based on the slug rather than the numeric ID. Simple, right?

But wait, there’s more! You can totally customize how slugs are generated with FriendlyId.

Define multiple slug candidates if the primary one’s taken:

class User < ApplicationRecord
  extend FriendlyId
  friendly_id :slug_candidates, use: [:finders, :slugged]

  def slug_candidates
    [
      :name,
      [:name, :description],
      [:name, :description, :created_at]
    ]
  end
end

This way, if the first candidate’s snagged, FriendlyId tries the next one. Perfection.

Want to control when a new slug is created? Override the should_generate_new_friendly_id? method:

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

  def should_generate_new_friendly_id?
    name_changed?
  end
end

This makes sure a new slug is generated only when the name attribute changes.

You can even make slugs based on custom methods, not just attributes:

class User < ApplicationRecord
  extend FriendlyId
  friendly_id :generate_random_slug, use: [:finders, :slugged]

  def generate_random_slug
    slug? ? slug : SecureRandom.uuid
  end
end

This is particularly handy for those one-of-a-kind or random slugs.

Plus, FriendlyId lets you maintain a history of your slugs. This means even if a URL changes, you can still access records via old slugs.

Enable slug history by tweaking your model:

class User < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: [:finders, :slugged, :history]
end

This will set up a new table to store that slug history, so you never lose access to old URLs.

Why should you bother with FriendlyId? Several reasons, my friend:

  • User-Friendly URLs: These slugs are far easier to read and remember, making user experience a bit of a joyride.
  • SEO Benefits: Search engines adore descriptive, keyword-rich URLs, giving you a bump in visibility.
  • Flexibility: So many options for customizing slug generation and dealing with conflicts.

Want to see an example workflow? Sure thing!

Begin by generating your app and model:

rails new my_app
cd my_app
rails generate scaffold user name:string slug:string:uniq
rails db:migrate

Add FriendlyId to your Gemfile:

gem 'friendly_id', '~> 5.2'

Then run:

bundle install

Configure your model:

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

Update your controller:

class UsersController < ApplicationController
  def show
    @user = User.friendly.find(params[:id])
  end

  private

  def set_user
    @user = User.friendly.find(params[:id])
  end
end

Generate slugs for existing records:

User.find_each(&:save)

Fire up the server and test it:

rails server

Now, watch as you can access user records via URLs like: http://localhost:3000/users/joe-schmoe instead of http://localhost:3000/users/1.

Follow these steps and customize FriendlyId to fit your needs. By doing so, you’ll craft user-friendly, memorable URLs for your Rails app, enhancing user experience and boosting your SEO game. Cheers to better URLs!

Keywords: FriendlyId, Ruby on Rails, user-friendly URLs, slug generation, SEO benefits, FriendlyId gem, Rails 5.0, Rails migration, custom slugs, slug history



Similar Posts
Blog Image
How to Build High-Performance WebRTC Apps in Ruby on Rails: Expert Guide 2024

Learn expert techniques for building efficient WebRTC applications in Ruby on Rails. From real-time communication to media handling, explore proven code examples and best practices to create reliable video chat solutions. Start building today.

Blog Image
Seamlessly Integrate Stripe and PayPal: A Rails Developer's Guide to Payment Gateways

Payment gateway integration in Rails: Stripe and PayPal setup, API keys, charge creation, client-side implementation, security, testing, and best practices for seamless and secure transactions.

Blog Image
6 Battle-Tested Techniques for Building Resilient Rails Service Integrations

Discover 6 proven techniques for building resilient Ruby on Rails service integrations. Learn how to implement circuit breakers, retries, and caching to create stable systems that gracefully handle external service failures.

Blog Image
7 Essential Ruby Metaprogramming Techniques Every Developer Should Master

Explore 7 essential Ruby metaprogramming techniques. Learn to create dynamic, flexible code with method creation, method_missing, eval methods, and more. Enhance your Ruby skills now.

Blog Image
Rust's Const Trait Impl: Boosting Compile-Time Safety and Performance

Const trait impl in Rust enables complex compile-time programming, allowing developers to create sophisticated type-level state machines, perform arithmetic at the type level, and design APIs with strong compile-time guarantees. This feature enhances code safety and expressiveness but requires careful use to maintain readability and manage compile times.

Blog Image
6 Powerful Ruby Testing Frameworks for Robust Code Quality

Explore 6 powerful Ruby testing frameworks to enhance code quality and reliability. Learn about RSpec, Minitest, Cucumber, Test::Unit, RSpec-Rails, and Capybara for better software development.