Reputation: 3553
Using Rails 5 with Friendly ID 5.1.0
Trying to understand how to update the slug when a Post
title is changed.
In the Friendly ID documentation it says you have to update the slug to nil
before you can save your updated slug.
Example
post = Post.first
post.title # "My first post"
post.slug = "my-first=post"
post.title = "My newer first post"
post.save!
post.slug # "my-first=post"
# Setting to nil first
post.slug = nil
post.title = "My newer first post"
post.save!
post.slug # "my-newer-first-post"
In my Post model I have set should_generate_new_friendly_id?
in hopes it will update the slug without manually setting the slug to nil
from the console or a web form.
# == Schema Information
#
# Table name: post
#
# id :integer not null, primary key
# title :string default(""), not null
# body :text default(""), not null
# created_at :datetime not null
# updated_at :datetime not null
# slug :string
#
# Indexes
#
# index_posts_on_slug (slug) UNIQUE
#
class Post < ApplicationRecord
extend FriendlyId
friendly_id :title, use: :history
private
def should_generate_new_friendly_id?
title_changed? || super
end
end
Is it the job of the should_generate_new_friendly_id?
method to update the slug if it's defined in your model?
Thanks again.
Upvotes: 1
Views: 1344
Reputation: 7361
Just add this method in your model:
def should_generate_new_friendly_id?
title_changed?
end
Upvotes: 3
Reputation: 1951
Looking at the source code, you should change the private method to:
def should_generate_new_friendly_id?
slug.blank? || title_changed?
end
For reference https://github.com/norman/friendly_id/blob/b6b6c004890ae3558a8ee19cc004a1456d9d0fff/lib/friendly_id/initializer.rb#L78
Upvotes: 2