Slugs in Rails using Friendly ID Gem

Slugs in Rails using ID gem

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.

Installation

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

add_column :groups, :slug, :string
add_index :groups, :slug, unique: true

rails g friendly_id

Model.find_each(&:save)

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

FriendlyId.defaults do |config|
       config.use :finders
       config.use :slugged
end

Group.create! name: “tech lead”

@group = Group.friendly.find(params[:id])

localhost:3000/groups/tech-lead

group1 = Group.create :name => "Tech lead"
group2 = Group.create :name => "Tech lead"
group1.friendly_id #=> "tech-lead"
group2.friendly_id #=>"tech-lead-f9f3789a-daec-4156-af1d-fab81aa16ee5"

class Group < ApplicationRecord
     extend FriendlyId
     friendly_id :name, use: :slugged
  def should_generate_new_friendly_id?
    name_changed?
  end
end

This is how you can add friendly_id to your models to make the user friendly and memorable URLs. and Also you can customize the methods of the FriendlyId module by extending it in your model.rb file.

Related posts

Java vs. Python: Top Programming Language Comparison

by Shardul Bhatt
4 years ago

How to send responsive Emails using MJML in Rails?

by Prina Patel
9 years ago

How To Use Python for FinTech Applications

by Parth Barot
5 years ago
Exit mobile version