我正在使用friendly_id gem处理URL Slug,并且当从documentation更改Slug时应用修补程序以避免404时,我的代码无法正常工作。
问题在于,当我单击“编辑”按钮时,它只是重定向到帖子的显示视图,并且因为它“无法找到ID为...的帖子”而不允许我发表新帖子,因为它使用的是find_post
方法。
我也有friendly_id_slugs
表来存储历史记录。
在我的帖子模型中:
class Post < ApplicationRecord
extend FriendlyId
friendly_id :title, use: :slugged
...
def should_generate_new_friendly_id?
slug.nil? || title_changed?
end
end
后置控制器:
class PostsController < ApplicationController
before_action :find_post
...
def find_post
@post = Post.friendly.find(params[:id])
# If an old id or a numeric id was used to find the record, then
# the request path will not match the post_path, and we should do
# a 301 redirect that uses the current friendly id.
if request.path != post_path(@post)
return redirect_to @post, :status => :moved_permanently
end
end
end
我尝试使用before_filter
,但问我是不是before_action
,并且已经在控制器的public和find_post
部分中尝试了private
方法
答案 0 :(得分:1)
在我看来,您可能想要跳过除show
之外的任何操作的重定向逻辑,因为redirect_to @post
仅将您带到演出路线。
def find_post
@post = Post.find params[:id]
if action_name == 'show' && request.path != post_path(@post)
return redirect_to @post, :status => :moved_permanently
end
end
或者,您可以通过以下方式将重定向行为与帖子的预加载脱钩:
before_action :find_post
before_action :redirect_to_canonical_route, only: :show
def find_post
@post = Post.find params[:id]
end
def redirect_to_canonical_route
if request.path != post_path(@post)
return redirect_to @post, :status => :moved_permanently
end
end