【问题标题】:Friendly_id preventing edit/new pages due to before_action :find_postFriendly_id 由于 before_action 阻止编辑/新页面:find_post
【发布时间】: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


【解决方案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

【讨论】:

  • 写before_action :find_post, only: :show会更传统
  • @TomLord 可能,但find_post 也可能对其他操作有用……您只是不想为所有操作重定向。另一个不错的选择是将其提取到单独的before_action :redirect_to_canonical_route, only: :show。
  • @TomLord 我已将此作为替代方案纳入我的答案中。
  • 将重定向行为与预加载分开处理有什么好处?有什么值得额外的代码吗?
  • @TomLord 我必须同意你的观点,我确实喜欢只需将 , only: :show 添加到我的代码中即可让一切正常工作的简单性。
猜你喜欢
  • 1970-01-01
  • 2019-10-06
  • 2015-08-10
  • 1970-01-01
  • 2010-11-17
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多