How to add Pretty URLs to an existing project

FriendlyId

  1. Add the gem to your gemfile.
    gem friendly_id
    
  2. After including FriendlyId, run the bundle command.
    bundle install
    
  3. In order to add FriendlyId to an existing application, we will need to create a migration to add the necessary field to the model we want to use FriendlyId with. We add uniq to enforce unique slug values.
    rails g migration AddSlugToPost slug:uniq
    
  4. Now we need to update our database:
    rake db:migrate
    
  5. Now, we need to add code to our model to tell rails that we wish to use FriendlyId. Open the desired model and add the following code.
    extend FriendlyId
    friendly_id :title, use: :slugged
    
  6. We are almost there! While technically we are all set up and good to go, existing data still doesn't have a slug. In order to add a slug, start a rails console:
    rails c
    
  7. Inside the rails console, run a command to loop through each model and save it:
    Posts.find_each(&:save)
    
  8. As a final step, we need to change our .finds to friendly finds.
    Post.find(params[:id])
    
    becomes
    Post.friendly.find(params[:id])
    
  9. Now it should work! Checkout out dem purrty URLs.