Friendly_id阻止由于before_action导致的编辑/新页面:find_post

问题描述 投票:0回答:1

我正在使用friendly_id gem处理URL Slugs,当应用修复程序以避免在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而且我在我的控制器的公共和find_post部分尝试了private方法。

ruby-on-rails ruby friendly-id
1个回答
1
投票

这听起来像你可能想跳过除了show动作以外的任何重定向逻辑,因为redirect_to @post只会将你送到show节目。

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
© www.soinside.com 2019 - 2024. All rights reserved.