【问题标题】:How to render two different error pages for same error code (e.g. 404) in a single rails application?如何在单个 Rails 应用程序中为相同的错误代码(例如 404)呈现两个不同的错误页面?
【发布时间】:2012-07-24 14:26:55
【问题描述】:

我有一个 Rails 应用程序,其中有两个部分,因此我想为错误页面使用两种不同的布局。

例如,如果错误来自第 1 部分,则应为错误 (404, 500) 使用 layout1 / 不同的页面。

如果错误来自第 2 部分,那么 layout2 / 不同的页面应该用于错误 (404, 500)。

我编写了代码来定义错误页面,启用了 erb 和 ruby​​ 代码。

在应用程序.rb中

config.exceptions_app = self.routes

在 routes.rb 中

match "/404", :to => "errors#error_404"
match "/500", :to => "errors#error_500"

【问题讨论】:

  • 嗨,我更新了我的答案。希望它有助于解决您的问题。

标签: ruby-on-rails


【解决方案1】:

更新

稍微考虑了一下。如果你只有几种类型的错误,那么这样做怎么样?

在您的routes.rb 的最最后一行,添加一个

match '/my_segment/*path', :to => 'errors#not_found'

这应该匹配任何未定义的路径(通常会抛出ActionController::RoutingError)并将其推送到您的全局错误页面。

您可以使用上面的分段通配符来玩游戏以获得正确的路径。这不应该影响您的预定义路径,例如mydomain.com/controller1

下面是更细粒度的控制方法。

这将帮助您匹配来自mydomain.com/some_controller/bad_params 的任何错误

def firstController < ApplicationController 
  def method_in_first_controller
    # Do something here
    rescue
      @error = # Error object here
      render :template=>"some_error_template", :status => :not_found # In specific action
  end
end


def secondController < ApplicationController 
  rescue_from ActiveRecord::RecordNotFound, :with => :rescue_not_found # In secondController

  def method_in_second_controller 
    # Do something  
  end

  protected
  def rescue_not_found
    @error = # Error object here
    render :template => 'some_error_template', :status => :not_found
  end

end

def ApplicationController 
  rescue_from ActiveRecord::RecordNotFound, :with => :rescue_not_found # Globally

  protected
  def rescue_not_found
    @error = # Error object here
    render :template => 'application/not_found', :status => :not_found
  end
end

使用referrer似乎无济于事,抱歉昨天回答不好。

【讨论】:

    【解决方案2】:

    在您的错误控制器中,您可以检查谁是引荐来源,并基于此进行条件布局

    【讨论】:

    • 如何查看推荐人?有没有具体的代码?
    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2016-06-06
    相关资源
    最近更新 更多