ruby-on-rails - 自定义404无法从 Controller 触发

标签 ruby-on-rails ruby ruby-on-rails-4 error-handling http-status-code-404

我尝试使用cms gem时处理404错误。在我以前的应用程序中,此404方法似乎可以工作,但现在无法解决该错误。有任何想法吗?

# application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  rescue_from ActionController::RoutingError, :with => :render_404

  def after_sign_in_path_for(resource)
    admin_cms_path
  end

private

  def render_404(exception = nil)
    if exception
      logger.info "Rendering 404: #{exception.message}"
    end
    flash[:error] = 'The page you entered is unavailble, please send us an email if this is unexpected'
    redirect_to root_path
  end
end

和路线
# routes.rb
Amskier::Application.routes.draw do
  # ...    
  comfy_route :blog_admin,        path: '/admin'
  comfy_route :cms_admin,         path: '/admin'

  root to: "cms/content#show"

  comfy_route :cms,               path: '/', sitemap: false
end

最佳答案

将路由添加到 Controller 的此操作:

match 'path' to: 'errors#catch_404'

并像这样创建错误 Controller
class ErrorsController < ApplicationController
  def catch_404
    raise ActionController::RoutingError.new(params[:path])
  end
end

之后,它应该开始工作。

关于ruby-on-rails - 自定义404无法从 Controller 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23476699/

相关文章:

ruby - 在 Ruby 中计算 Base-n 对数

ruby-on-rails - 如何使主页上的表单重定向回而不是它自己的 View

ruby-on-rails - 如何为 belongs_to 本身的 Rails 模型编写迁移

ruby-on-rails - 通过 Ruby 中的 MassiveRecord 的 HBase 导致中止

html - 在 HAML 的 Markdown 中转义 HTML

jquery - 使用 Ajax 的 Rails Kaminari 分页

ruby-on-rails - Carrierwave 不会在模型更新后重新创建版本

arrays - 数组格式的 Ruby PG gem 选择字段

ruby-on-rails - Heroku Rails Force SSL 重定向循环

ruby-on-rails - 我可以将默认值传递给 rails 生成迁移吗?