【发布时间】:2019-03-11 21:35:54
【问题描述】:
我正在使用 friendly_id gem 来处理 URL Slugs,当 slug 从 documentation 更改时应用修复以避免 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,我已经在控制器的公共部分和private 部分尝试了find_post 方法。
【问题讨论】:
-
post_path是 show 动作,而您正在执行 edit 动作 - 因此这将始终重定向。您是否真的希望before_action触发edit操作? -
@TomLord 哦,不,我实际上不是,因为它始终是通过
@post = Post.friendly.find(params[:id])获得的最新 URL 我只想从文档中实现它以解决任何旧 URL,以防万一我更新它们。
标签: ruby-on-rails ruby friendly-id