【问题标题】:Rails 5 catch-all for request formatsRails 5 包罗万象的请求格式
【发布时间】:2018-09-04 22:47:04
【问题描述】:

在 Rails 5 routes.rb 中,最后我有一个包罗万象的内容:

match "*path" => "static_pages#not_found", via: :all

结合操作,这可以很好地处理无用的 URL,例如“/bla”或“/bla.html”。但是对于具有不同请求格式的现有路由,这是行不通的。例如,我有工作 URL“/authors”,而无用的“/authors.jpg”正在获取:

AuthorsController#index is missing a template for this request format and variant. request.formats: ["image/jpeg"] request.variant: []

关于开发和生产的 HTTP 406。

我希望即使我的 not_found 操作也能处理未处理的请求格式。什么是 Rails 5 方法来捕获所有请求格式?

来源是https://github.com/muhme/quote

【问题讨论】:

    标签: ruby-on-rails routing ruby-on-rails-5


    【解决方案1】:

    您应该能够在您的路由中使用默认值,以便对您的路由更加严格。我不相信这是最好的选择虽然http://guides.rubyonrails.org/routing.html#defining-defaults

    defaults format: :html do
      resources :authors
    end
    

    我认为更好的解决方案是rescue_from http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from

    rescue_from 中使用ActionView::MissingTemplate。我可能会设置某种错误通知,但当这些仍然发生时提醒您。

    rescue_from ActionView::MissingTemplate do |exception|
      # render 404 and/or email yourself a notification
    end
    

    【讨论】:

    • 嘿@dft,谢谢您的回答。我尝试在路线中设置默认格式,但没有任何效果。 /authors.jpg 或 /authors/1.jpg 仍在引发 ActionController::UnknownFormat
    • 和rescue_from ActionView::MissingTemplate 或ActionController::UnknownFormat 在ApplicationController 也显示没有效果(异常没有被捕获)
    • 你是正确的捕捉是正确的方式,现在为我工作第二次尝试,thx
    【解决方案2】:

    最终为我工作的是ApplicationController:

    rescue_from ActionController::UnknownFormat do |exception|
      redirect_to(controller: 'static_pages', action: 'not_found', original_url: request.original_url)
    end
    

    配合相应的动作:

    def not_found
      @original_url = params[:original_url]
      if @original_url.blank?
        @original_url = request.original_url
      end
    
      respond_to do |format|
        format.all { render :status => 404, :formats => 'html', content_type: "text/html" }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 2011-07-23
      • 2011-02-12
      相关资源
      最近更新 更多