-
-
Notifications
You must be signed in to change notification settings - Fork 592
Tips and Tricks
John Yeates edited this page Jun 9, 2018
·
17 revisions
Feel free to add any helpful hints for other users here.
Submitted by maxcal
Case:
We want our post class to have slug and title attributes 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.empty? && title_changed?
end
end
Submitted by benpolinsky
Case:
We want our Post to have an editable slug that doesn't default to another field. The record's id will be used if no slug is set.
example output:
post = Post.create(title: "How Long is a Long Long Time")
post.slug
# nil
post = Post.update_attributes(title: "Some other title", temporary_slug: "My favorite post)
post.slug
# 'my-favorite-post'
class Post < ActiveRecord::Base
attr_accessor :temporary_slug
extend FriendlyId
friendly_id :slug, :use => [:slugged]
def should_generate_new_friendly_id?
temporary_slug_changed?
end
# track changes in non persisted attribute
def temporary_slug=(value)
attribute_will_change!('temporary_slug') if temporary_slug != value
@temporary_slug = value
end
def temporary_slug_changed?
changed.include?('temporary_slug')
end
end