我正在使用friendly_id
5.0.0.rc1,还有active_admin
。
除了在active_admin中更新记录的slug
属性/列没有做任何事情(它保持不变)之外,所有内容都会按预期完美地运行。
我发现只使用控制台的行为相同:
p = Post.first
p.slug
#=> 'test'
p.slug = 'another-test'
p.save
#=> true
p.slug
#=> 'test
我的配置:
FriendlyId.defaults do |config|
config.use :reserved
config.reserved_words = %w(admin new edit index session users register)
config.use :finders
config.use :slugged
config.slug_column = 'slug'
config.sequence_separator = '-'
config.use Module.new {
def should_generate_new_friendly_id?
slug.blank? || slug_changed?
end
}
end
我的模特:
class Post < ActiveRecord::Base
default_scope { order('created_at DESC') }
validates :title, presence: true
validates :body, presence: true
validates :views, presence: true, numericality: { only_integer: true }
extend FriendlyId
friendly_id :title, use: [:slugged, :history]
end
我的控制员:
class PostsController < ApplicationController
def index
@posts = Post.all.page(params[:page]).per(10)
end
def show
@post = Post.find_by_slug!(params[:id])
if request.path != post_path(@post)
redirect_to @post, :status => :moved_permanently and return
else
@post.increment :views if @post
end
end
end
谢谢!
答案 0 :(得分:22)
通常在使用友好ID时,您永远不会手动更新slug。代替:
def should_generate_new_friendly_id?
slug.blank? || title_changed?
end
然后每次更改标题时,它都会自动更新slug。
答案 1 :(得分:1)
更确切地说,您应该使用self.title_changed?
def should_generate_new_friendly_id?
slug.blank? || self.title_changed?
end
答案 2 :(得分:0)
以防万一其他人来到这里,只需要换一个子弹:
p = Post.first
p.slug
#=> 'test'
tmp_title = p.title
p.title = 'another-test'
p.slug = nil
p.save
#=> true
p.title = tmp_title
p.slug
#=> 'another-test'