友情ID不更新slug

时间:2016-07-19 00:31:51

标签: ruby-on-rails ruby-on-rails-5 friendly-id

使用带有友好ID 5.1.0的Rails 5

尝试了解更改Post标题时如何更新slug。

在Friendly ID文档中,它表示您必须先将slug更新为nil,然后才能保存更新的slug。

实施例

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"

在我的Post模型中,我设置了should_generate_new_friendly_id?,希望它能够更新slug而无需从控制台或Web表单手动设置slug到nil

# == 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

如果在模型中定义了slug,那么更新slug是should_generate_new_friendly_id?方法的工作吗?

再次感谢。

2 个答案:

答案 0 :(得分:1)

只需在模型中添加此方法:

def should_generate_new_friendly_id?
 title_changed?
end

答案 1 :(得分:0)

查看源代码,您应该将私有方法更改为:

def should_generate_new_friendly_id?
  slug.blank? || title_changed?
end

供参考https://github.com/norman/friendly_id/blob/b6b6c004890ae3558a8ee19cc004a1456d9d0fff/lib/friendly_id/initializer.rb#L78