Friendly_id gem in Rails
.FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL's and work with human-friendlystrings as if they were numeric ids for ActiveRecord models.
Usage
Add this line to your application's Gemfile:
gem 'friendly_id', '~> 5.2.4' # Note: You MUST use 5.0.0 or greater for Rails 4.0+
And then execute:
bundle install
Add a
slug
column to the desired table (e.g. Users
)rails g migration AddSlugToProducts slug:uniq
Generate the friendly configuration file and a new migration
rails generate friendly_id
Note: You can delete the
CreateFriendlyIdSlugs
migration if you won't use the slug history feature. (Read more)
Run the migration scripts
rails db:migrate
Edit the
app/models/product.rb
file as the following:class Product < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
end
Edit the
app/controllers/users_controller.rb
file and replace User.find
by User.friendly.find
class ProductController < ApplicationController
def show
@product = Product.friendly.find(params[:id])
end
end
Now when you create a new user like the following:
User.create! name: "Joe Schmoe"
You can then access the user show page using the URL http://localhost:3000/products/joe-schmoe.
If you're adding FriendlyId to an existing app and need to generate slugs for existing users, do this from the console, runner, or add a Rake task:
Product.find_each(&:save)
POSTED BY-MANISH SINGH DATE-19 SEP 2019
Comments
Post a Comment