-
-
Notifications
You must be signed in to change notification settings - Fork 589
Tips and Tricks
Ben Polinsky edited this page Jun 22, 2016
·
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.blank? || title_changed?
end
endSubmitted by benpolinsky
Case:
We want our Post to default to an ID unless the slug is set by the user.
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?
slug.blank? || title_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