Routing with Friendly IDs in Rails

Imagine you have a fruit shop application built in Ruby on Rails. As a Rails developer, you know that to get to a specific fruit page, a URL like www.myfruitshop/1 will work - but it’s more user friendly to use something like this:

1
www.myfruitshop/banana

This article will show you how to implement this in a Ruby on Rails application.

First, create an application and fruit model to implement the functionality.

1
2
3
4
rails new fruits-app
cd fruits-app
rails generate scaffold Fruit name slug:uniq:index
rails db:create db:migrate

In your Gemfile, add the friendly_id gem.

1
gem 'friendly_id', '~> 5.2.4'

Now run the following command to generate the config file and a new migration:

1
rails generate friendly_id

Run the following commands:

1
2
bundle install
rails db:migrate

In app/models/fruit.rb, make sure you have the following lines:

1
2
3
extend FriendlyId
friendly_id :name, use: :slugged

In app/controllers/fruits_controller, make sure your set_fruit method looks like this:

1
2
3
def set_fruit
 @fruit = Fruit.friendly.find(params[:id])
end

Remove the following lines from app/views/fruits/_form.html.erb:

1
2
3
4
<div class="field">
  <%= form.label :slug %>
  <%= form.text_field :slug %>
</div>

Now go to http://localhost:3000/fruits and click New Fruit. Add a new fruit and it will redirect you to http://localhost:3000/fruits/banana.

Screen Shot 2020-06-05 at 3.26.17 PM.png

The application is now using Friendly IDs!