Skip to content
Paul Götze edited this page Mar 6, 2016 · 17 revisions

FriendlyId Tips and Tricks

Feel free to add any helpful hints for other users here.

User editable slug - with defaults

Submitted by maxcal

Case:

We want our post class to have slug and title attribues that are editable by the user. The user should be able to edit the title and slug independently. The slug should default to a slugged version of the title.

example output:

post = Post.create(title: "How Long is a Long Long Time", slug: 'how-long')
post.slug 
# 'how-long'
post = Post.create(title: "How Long is a Long Long Time")
post.slug 
# 'how-long-is-a-long-long-time'
class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, :use => [:slugged]
  validates_presence_of :title

  def should_generate_new_friendly_id?
    slug.blank? || title_changed?
  end
end

Clone this wiki locally