DEV Community

BoTree Technologies
BoTree Technologies

Posted on • Originally published at botreetechnologies.com on

Slugs in Rails with FriendlyID (Example)

Slugs in Rails with FriendlyID

FriendlyId is a very good gem which allows you to replace ids in your URLs with strings. This lets your Rails app work with ‘friendly’ URLs like ‘myapp /users/john’ as opposed to ‘myapp/users/1’.

Ruby on Rails development company considers this gem as most essential for Rails applications due to its ability to make links memorable.

Let’s start with how to use this gem in a Rails application by following below.

1. Installation

  • The very first step you have to follow is to install the gem.
  • Add in your Gem file:gem 'friendly_id', '~> 5.2' # Note: MUST use 5.0.0 or greater for Rails 4.0+
  • Then execute ‘bundle install’.
  • Next step is to add a slug column to the model on which you want a friendly_id.
  • Here, I have a model called “Group” on which I am going to add a slug column.
    rails g migration add_slug_to_groups slug:string:uniq
    rails db:migrate

  • In db/migrate/add_slug_to_groups.rb you have the following:
    add_column :groups, :slug, :string
    add_index :groups, :slug, unique: true

  • Now open the rails console and generate a configuration file for friendly_id.

rails g friendly_id

  • If you are implementing friendly_id in your existing model, then you have to run the following command in the rails console to generate their slugs.

Model.find_each(&:save)

  • In my case, Group.find_each(&:save)
  • Let’s extend or include the friendly_id module in our model to access the methods defined in it.
  • In models/group.rb, we have a name column for the group on which we are going to add a friendly_id.

The post Slugs in Rails using Friendly ID Gem appeared first on BoTree Technologies.

Top comments (0)