Skip to content
Norman Clarke edited this page Dec 10, 2013 · 17 revisions

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_prescence_of :title

  def should_generate_new_friendly_id?
    if !slug?
      name_changed?
    else
      false
    end
  end
end

Clone this wiki locally