Ruby on rails 在默认情况下,如何将Rails控制器设置为仅接受HTML请求?

Ruby on rails 在默认情况下,如何将Rails控制器设置为仅接受HTML请求?,ruby-on-rails,Ruby On Rails,我的大多数控制器在HTML中只有有意义的响应。考虑下面的场景: 我做了一个简单的控制器 class FrontController < ApplicationController def index end end 其次,我可以使用respond\u with,尽管在一个不代表资源的控制器中它看起来很奇怪: class FrontController < ApplicationController respond_to :html def index re

我的大多数控制器在HTML中只有有意义的响应。考虑下面的场景:

我做了一个简单的控制器

class FrontController < ApplicationController
  def index
  end
end
其次,我可以使用
respond\u with
,尽管在一个不代表资源的控制器中它看起来很奇怪:

class FrontController < ApplicationController
  respond_to :html

  def index
    respond_with # No arguments, because there's nothing to put here.
  end
end
class FrontController
其中任何一个都将以
406
响应XML请求。但是,两者都需要向每个控制器操作添加代码


以下是我希望能够做到的:

  • 理想情况下,如果找不到模板,我希望隐式呈现(不声明
    render
    调用或显式格式)的操作返回
    406
    。对于Rails来说,这似乎是一个合理的默认设置,我很惊讶它还没有做到这一点

  • 如果做不到这一点,我至少希望能够在默认情况下将
    :html
    声明为我所有控制器的唯一可接受格式(并允许单个控制器和操作中的任何显式格式声明覆盖该格式)

想法


(Rails 4.0.1、Ruby 2.0.0)

如果您不想使用Responses\u to,可以执行以下操作:

class ApplicationController < ActionController::Base
  before_filter :allow_only_html_requests

  ...

  def allow_only_html_requests
    if params[:format] && params[:format] != 'html'
      render :file => "#{RAILS_ROOT}/public/404.html"
    end
  end

  ...

end
class ApplicationController“#{RAILS_ROOT}/public/404.html”
结束
结束
...
结束

这太严格了。我只想
:html
-只有在没有明确提供其他格式的情况下才是默认格式。(此外,响应应将状态设置为
:not_acceptable
,并且呈现html响应可能不是响应除html以外的特定请求的最佳方式。):)这并不能回答您的问题,但是它包含了很多相关信息&可能对其他路过你的问题的人有帮助:。我想这就是你要找的
class ApplicationController < ActionController::Base
  before_filter :allow_only_html_requests

  ...

  def allow_only_html_requests
    if params[:format] && params[:format] != 'html'
      render :file => "#{RAILS_ROOT}/public/404.html"
    end
  end

  ...

end