Friday, 27 September 2019

FriendlyId

FriendlyId 

It lets you create pretty URLs and work with human-friendly strings as if they were numeric ids.

   # without FriendlyId
     http://example.com/states/4323454

   # with FriendlyId
     http://example.com/states/washington
  
 1. 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
2. Add a slug column to the desired table (e.g. Users)
         rails g migration AddSlugToUsers slug:uniq

3. Generate the friendly configuration file and a new migration
      rails generate friendly_id
      Run the migration scripts  rails db:migrate 
 
4. Edit the app/models/user.rb file as the following: 
     
     class User < ApplicationRecord
        extend FriendlyId
        friendly_id :name, use: :slugged
     end
 
 5. Edit the app/controllers/users_controller.rb file and replace User.find by   
    User.friendly.find

     class UserController < ApplicationController
       def show
         @user = User.friendly.find(params[:id])
       end
     end
 
6. Now when you create a new user like the following:
      User.create! name: "Joe Schmoe"
 
7. You can then access the user show page using the URL http://localhost:3000  
     /users/joe-schmoe.


Schema :-  

create_table "products", force: :cascade do |t|
    t.string "name"
    t.string "description"
    t.integer "price"
    t.string "image"
    t.integer "category_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.float "full_price"
    t.datetime "deleted_at"
    t.index ["deleted_at"], name: "index_products_on_deleted_at"
    t.index ["slug"], name: "index_products_on_slug", unique: true
  end 

Friendly Id Schema 

create_table "friendly_id_slugs", force: :cascade do |t|
    t.string "slug", null: false
    t.integer "sluggable_id", null: false
    t.string "sluggable_type", limit: 50
    t.string "scope"
    t.datetime "created_at"
    t.index ["slug", "sluggable_type", "scope"], name:  "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
    t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
    t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
  end 
 


     
 
 

No comments:

Post a Comment

  Common Git Commands   Take clone of a repository git clone <remote-repository-url> ex: git clone  https://github.com/agricor/RegTech...