[英]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.