假设您有一个模型
Speaker
,它利用 FiendlyId gem 来创建像这样的独特的鼻涕虫:
class Speaker < ApplicationRecord
friendly_id :name, use: %i[slugged history finders]
end
并且您正在使用 CanCanCan gem 在您的应用程序中实现授权。因此,在您的
SpeakersController
中,您正在加载和授权这样的资源:
class SpeakersController < ApplicationController
load_and_authorize_resource
# GET /speakers
def index; end
# GET /speakers/1
def show; end
end
并且你正在使用相同的方法在其他控制器中加载和授权资源。
如何在更改扬声器名称时利用 FiendlyId gem 中的
history
插件将像 /speakers/falde-ali
这样的旧 slug 重定向到像 /speakers/ali-fadel
这样的新 slug,而无需在每个控制器中实现特定方法来处理它?
基本上,您可以像这样在
app/controller/concerns
内部实现一个关注点:
# app/controller/concerns/slug_redirector.rb
module SlugRedirector
extend ActiveSupport::Concern
included do
before_action :redirect_to_canonical_route
end
def redirect_to_canonical_route
record = get_record(model)
return if record.blank?
canonical_path = get_canonical_path(record)
redirect_to canonical_path, status: :moved_permanently if should_redirect?(canonical_path)
end
private
def model
controller_name.classify.constantize
end
def namespace
self.class.module_parent_name&.downcase&.to_sym
end
def get_record(model)
instance_variable_get("@#{model.name.underscore}")
end
def get_canonical_path(record)
polymorphic_path([namespace, record])
end
def should_redirect?(canonical_path)
request.path != canonical_path
end
end
然后将其包含在加载和授权调用下方的控制器中,如下所示:
class SpeakersController < ApplicationController
load_and_authorize_resource
include SlugRedirector
# GET /speakers
def index; end
# GET /speakers/1
def show; end
end
这个问题使用 FriendlyId gem 实现了到最新 slug 的重定向。
关注点包括调用
before_action
方法的 redirect_to_canonical_route
。此方法从控制器的实例变量中检索记录,然后使用 polymorphic_path
方法生成规范路径。如果当前请求路径与规范路径不匹配,该方法使用 redirect_to
. 发出到规范路径的永久重定向
这个问题提供了一种方法来确保将带有旧的或过时的 slug 的 URL 重定向到最新版本的 URL。这有助于维护 SEO 并确保用户始终被定向到正确的页面。
希望对您有所帮助:)