What should we do if we have to generate slug for a model when its associated records are updated. For example I am using models User and UserProfile and the slug is user.user_profile.name. When a new user is created the associated user_profile is also saved. The slug is generated for a new user record. But when updating the user_profile and the name is changed, the slug is not updated. Please help.
Asked
Active
Viewed 169 times
2 Answers
1
In a recent version of friendly_id, you can define a method to specify when to regenerate the slug (although this is probably not what you need):
def should_generate_new_friendly_id?
name_changed? || super
end
You could use an after save callback on the UserProfile class to set the slug to nil and force friendly_id to regenerate the slug:
if name_changed?
user.slug = nil
user.save
end
That should take care of it according to the docs: http://norman.github.io/friendly_id/

Tom Fast
- 1,138
- 9
- 15
-1
You can override the should_generate_new_friendly_id?
method. This way you can control when a new slug is being generated.
You could do something like this
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :my_friendly_id_method, :use => :slugged
def should_generate_new_friendly_id?
user_profile.changed?
end
end

Arjan
- 6,264
- 2
- 26
- 42