如何捕获和重定向有效但无效的资源 ID 的 rails 路由?

ahn*_*cad 2 redirect routes ruby-on-rails path http-status-code-404

match '*path' => redirect('/'), via: :all if Rails.env.production? 很好地处理事情,但它不能正确地捕捉这样的情况

/root.com/articles/293 其中 293 是数据库中不存在的文章 ID。

在这种情况下,它仍然重定向到默认的 404 页面,这在 heroku 上是丑陋的“出现问题”页面。

如何利用“有效的 url,但无效的资源 ID” url 来控制其重定向到我想要的位置?

mes*_*jah 5

退房rescue_from。当您想偏离 Rails 显示 404 页面的默认行为时,它非常方便。

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

  private

  def record_not_found
    # handle redirect
  end
end
Run Code Online (Sandbox Code Playgroud)