Reputation: 1653
We're ending up with a lot of
ActionView::MissingTemplate (Missing template presentations/show, application/show with {:locale=>[:en], :formats=>["image/*"], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}
in our logs.
The application only does HTML for the moment so I would like all other formats to return 406 (or something). Is there any way to set this once for all render calls? Or do we have to sprinkle respond_to
everywhere?
Thanks!
Upvotes: 4
Views: 527
Reputation: 19938
If you do not use respond_with
or want ActionView::MissingTemplate
to be raised before the action is run (i.e. to prevent models being fetched etc.) you can use verify_requested_format! from the responders gem.
class UsersController < ApplicationController
respond_to :html
before_action :verify_requested_format!
def index
# ...
end
end
Then verify:
curl -v -H "Accept: image/*" localhost:9000/users
< HTTP/1.1 406 Not Acceptable
Incidentally you can also use respond_with
without passing on a model instance such as:
class UsersController < ApplicationController
respond_to :html
def index
@users = User.all
respond_with
end
end
This however does not seem to be documented as far as I can see.
Upvotes: 0
Reputation: 1653
I ended up going with a mix match of solutions since I couldn't get respond_to
to work. This will send a 406 each time someone tries some unsupported mime type.
before_filter :ensure_html
def ensure_html
head 406 unless request.format == :html
end
Upvotes: 1
Reputation: 4778
You could add a rescue_from
line to ApplicationController.rb
:
class ApplicationController < ActionController::Base
rescue_from ActionView::MissingTemplate do |e|
render nothing: true, status: 406
end
# ...
end
If I try to access document.xml
(rather than document.pdf
) in my Rails application, Firefox shows the following message in the browser console:
GET http://localhost:3000/quotes/7/document.xml [HTTP/1.1 406 Not Acceptable 29ms]
Upvotes: 1
Reputation: 12320
You can do it by following way
class UsersController < ApplicationController
respond_to :html
def index
@users = User.all
respond_with(@users)
end
end
It will respond
html all actions
of users
controller
Or If you want to respond_to for all controller
then add it to ApplicationController
just do
class ApplicationController < ActionController
respond_to :html
end
and
class UsersController < ApplicationController
def index
@users = User.all
respond_with(@users)
end
end
Upvotes: 0