本文介绍了Rails 4 友好 Id Slug 未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容:

gem 'friendly_id', github: 'FriendlyId/friendly_id', branch: 'master'

我正在我的 Rails 4 网站上创建一个文章部分.我遇到的问题是,当我更改现有文章的名称时,slug 不会更新.

I am creating an Article section on my Rails 4 website. The problem I am having is that when I change a existing article's name the slug is not updated.

这是我目前所拥有的:

extend FriendlyId
friendly_id :name, use: :slugged

add_column :articles, :slug, :string
add_index :articles, :slug, unique: true

推荐答案

In FriendlyId 4 (Rails 3 compatible) 有一个方法

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

should_generate_new_friendly_id?

并且您可以在模型上定义它以控制何时重新生成 slug.试试

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

def should_generate_new_friendly_id?
  name_changed?
end

在名称更改时重新生成 slug.

to regenerate slug when name changes.

编辑

FriendlyId 版本 5(与 Rails 4 兼容)不再在保存时重新生成 slug.要恢复此功能,您可以在保存之前将 slug 列设置为 nil 或使用上面提供的解决方案.

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.

编辑 2

你需要覆盖 slug setter 来保存你的 Rails <5 &FriendlyId > 5 如本问题中所述.

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

将此添加到模型文件

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

这篇关于Rails 4 友好 Id Slug 未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:49