We’re going to be setting up a rails gem called friendly_id which cleans up our URLs. The URL for a user profile page currently looks something like http://memespace.xyz/users/1 (where the user id is the number 1). We’d rather it look something like http://memespace.xyz/users/alexander-paterson. Friendly ID will generate some database migrations that add a table for storing alternative, more meaningful ID’s for objects (in our case just users).

As I do this, I’m referring to the friendly_id github repo as a guide. Usually the most helpful information about a gem is found on its github repository.

First add the gem to your Gemfile:

### Gemfile

...
gem 'friendly_id'

and run bundle install.

Get friendly_id to generate the new database migration it requires with rails generate friendly_id. Open up the new migration file and add the following line:

### db/migrate/20160428024451_create_friendly_id_slugs

...
    add_column :users, :slug, :string, unique: true
  end
end

Now run rake db:migrate. Finally, we just need to tell our user model that it’s going to be using friendly_id.

### app/models/user.rb

class User < ActiveRecord::Base
  has_many :posts
  default_scope { order(created_at: 'DESC') }
  
  extend FriendlyId
  friendly_id :slug_candidates, use: [:slugged, :finders]
  
  # Try building a slug based on the following fields in
  # increasing order of specificity.
  def slug_candidates
    [
      :name,
      [:name, :id]
    ]
  end
...

use: [:finders] here tells friendly_id to override the User.find(:id) method so that friendly id’s work. Without this, we’d have to change all occurrences of User.find to User.friendly.find.

The last step is to generate the friendly ID slugs for our existing users. Slugs are automatically generated for new users, but not existing ones. So boot up rails console and run User.find_each(&:save).

And that’s it! Now if you start (or restart) your server, you should see the new URL style in use.

Friendly ID In Action

Deploy to heroku, as always:

git add -A
git commit -am "Added friendly_id"
git push heroku master
heroku run rake db:migrate

Remember to run heroku run rails console and execute User.find_each(&:save).

In the next chapter, we’re going to add an infinite-scroll effect to our news feed.