Setup Friendly Id's 5 For Rails

Posted By Weston Ganger

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])
end

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] ]
  end
end

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

Post.find_each(&:save)


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]

Article Topic:Software Development - Rails

Date:June 18, 2014