[英]Disable other formats than HTML in Rails 4?
我们最终得到了很多
ActionView::MissingTemplate (Missing template presentations/show, application/show with {:locale=>[:en], :formats=>["image/*"], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}
在我们的日志中。
该应用程序目前仅执行HTML,因此我希望所有其他格式返回406(或其他)。 有没有办法为所有渲染调用设置一次? 或者,我们是否必须respond_to
?
谢谢!
您可以将rescue_from
行添加到ApplicationController.rb
:
class ApplicationController < ActionController::Base
rescue_from ActionView::MissingTemplate do |e|
render nothing: true, status: 406
end
# ...
end
如果我尝试在我的Rails应用程序中访问document.xml
(而不是document.pdf
),Firefox会在浏览器控制台中显示以下消息:
GET http://localhost:3000/quotes/7/document.xml [HTTP/1.1 406 Not Acceptable 29ms]
我最终得到了一个混合的解决方案,因为我无法respond_to
工作。 每次有人尝试某些不受支持的mime类型时,这将发送406。
before_filter :ensure_html
def ensure_html
head 406 unless request.format == :html
end
在ApplicationController中放置respond_to :html
你可以通过以下方式完成
class UsersController < ApplicationController
respond_to :html
def index
@users = User.all
respond_with(@users)
end
end
它将respond
html users
controller
所有actions
或者如果您想响应所有控制器的响应
然后将它添加到ApplicationController
class ApplicationController < ActionController
respond_to :html
end
和
class UsersController < ApplicationController
def index
@users = User.all
respond_with(@users)
end
end
如果你没有使用respond_with
或者想要在运行动作之前引发ActionView::MissingTemplate
(即为了防止模型被提取等),你可以使用verify_requested_format! 来自响应者的宝石。
class UsersController < ApplicationController
respond_to :html
before_action :verify_requested_format!
def index
# ...
end
end
然后验证:
curl -v -H "Accept: image/*" localhost:9000/users
< HTTP/1.1 406 Not Acceptable
顺便提一下,您也可以使用respond_with
而不传递模型实例,例如:
class UsersController < ApplicationController
respond_to :html
def index
@users = User.all
respond_with
end
end
然而,据我所知,这似乎没有记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.