Rails 4 Friendly Id Slug Not Updating

会有一股神秘感。 提交于 2019-12-03 09:46:52
Mike Szyndel

In FriendlyId 4 (Rails 3 compatible) there was a method

should_generate_new_friendly_id?

and you could define it on your model to control when slug is regenerated. Try

def should_generate_new_friendly_id?
  name_changed?
end

to regenerate slug when name changes.

EDIT

FriendlyId version 5 (Rails 4 compatible) doesn't regenerate slugs on save anymore. To restore this functionality you can either set slug column to nil before saving or use the solution provided above.

EDIT 2

You need to override the slug setter for your saves to work for Rails <5 & FriendlyId > 5 as referenced in this issue.

Add this to the model file

  def slug=(value)
    if value.present?
      write_attribute(:slug, value)
    end
  end

I have this issues and just want to point out what I've noticed.

if you only do as in docs

class Post < ActiveRecord::Base
 extend FriendlyId
 friendly_id :title, use: :slugged
end

and then run Post.find_each(&:save) - slug is gonna get updated...

However in my case, I also have these in my model

class Post < ActiveRecord::Base
 extend FriendlyId
 friendly_id :title, use: :slugged

 def normalize_friendly_id(text)
   text.to_slug.normalize(transliterations: :russian).to_s
 end

 def should_generate_new_friendly_id?
   title_changed?
 end
end

with the code above it won't do anything when you run Post.find_each(&:save) I assume since your title doesn't change. (first method handles russian language)

so when working with the first model all worked great, but then when I copied ready code to next model I wanted to slugify, I run into some issues. Hope it helps someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!