Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Using friendly_id gem or slugged id in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 412
    Comment on it

    What friendly gem can do?

    Friendly_Id is the "Swiss Army bulldozer" of slugging and permalink plugins for Active Record. It lets you create pretty URLs and work with human-friendly strings as if they were numeric ids.


    Rails Quicksetup


    #Lets include this in the Gemfile
    gem 'friendly_id', '~> 5.1.0' # Note: You MUST use 5.0.0 or greater for Rails 4.0+
    rails generate friendly_id
    rake db:migrate

    You can use it in any model for example lets take the user model first:

    # edit app/models/user.rb
    class User < ActiveRecord::Base
      extend FriendlyId
      friendly_id :name, use: :slugged
    User.create! name: "Joe Schmoe"
    # Change User.find to User.friendly.find in your controller

    Now, the thing you notice here is that what if we want a custom URL besides the name, then you can use something like this:

    class Event < ActiveRecord::Base
    	extend FriendlyId
      	friendly_id :cus_name, use: :slugged
    	def custome_name 
             #using this function will make URL with description+name fields in events table
    	def cus_name #randon string will be generated of 5 characters 
    	def random_str leng=5 
      		leng.times{str+=([*('a'..'z'), *(1..9)]).shuffle.sample.to_s}

    rails server

    # 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:

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: