How To Setup Friendly Id's 5 For Rails

Posted by Weston Ganger on June 19, 2014

Here are the steps to setup FriendlyId's to your current rails app.

First add your gem and bundle install

gem 'friendly_id', '~> 5.0.0'

Next change your models controller

def show
  @post = Post.friendly.find(params[:id])

Then change your model file, the slug candidates section tell it to just use the title, if it already exists, use the next, if that exists next etc.

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: :slugged

  def slug_candidates
    [ :title,[:title,:id] ]

Generate a migration

rails g migrate add_slug_to_posts slug:string
rake db:migrate

Backup your database, then re-save your posts with the following command in the rails console


If you find you are having the issue Post not found with 'id'=test

In Controller Change:

Post.friendly.find to Post.find

In Model add:

use: [:slugged,:finders]

Posted in Rails and Tagged with friendly_ids rails 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts