5

Am i doing something wrong ? on Record update, slug is not being updated.

 class Company < ActiveRecord::Base
 extend FriendlyId

 friendly_id :name, use: [:slugged, :finders]

 def should_generate_new_friendly_id?
     true
 end

I'm using:

 friendly_id (5.0.4)
 Rails 4.1.7
 ruby 2.1.3p242 (2014-09-19 revision 47630)

This is how I'm trying in terminal:

  c = Company.last
  c.slug = nil 
  c.name = "testing abb"
  c.save
  c.reload
  c.slug // nil 
  c.name // testing abb

at the time of create: it inserts the slug but doesnt update on record update. any idea ?

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
kashif
  • 1,097
  • 4
  • 17
  • 32
  • hey, did you get things working? cause I see you neither have accepted my answer nor posted your solution – Andrey Deineko Dec 09 '15 at 09:44
  • Possible duplicate: https://stackoverflow.com/questions/17764359/rails-4-friendly-id-slug-not-updating/17765270 – Rimian Feb 03 '21 at 22:53

2 Answers2

11

Add :history to friendly_id :name, use: %i(slugged finders):

friendly_id(:name, use: :i[slugged history finders])

and override should_generate_new_friendly_id method to meet your needs:

 # will change the slug if the name changed
 def should_generate_new_friendly_id?
   name_changed?
 end
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • I already override the `should_generate_new_friendly_id?` as i mentioned above in the code. but i figured it out. the problem is that Model.rb file is too large and i didnt notice the `should_generate_new_friendly_id?` is already defined in the end of the file by some other developer :) – kashif Jan 22 '15 at 07:18
  • There is no such thing, as `model.rb` "didnt notice" something.. Your method is not working, because you don't tell it what changes to track, but simply return `true`. Follow the guidance I've provided and it will work – Andrey Deineko Jan 22 '15 at 07:20
  • Andrey, I believe that kashif simply meant that he/she did not notice that the model class already had this method defined. – Devon Kiss Oct 03 '20 at 02:24
0

As per the below post, slug is not changed in friendly_id 5 and above on record update.

Rails 4 Friendly Id Slug Not Updating

Vasu M
  • 31
  • 1