简体   繁体   中英

Disable other formats than HTML in Rails 4?

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!

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]

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

在ApplicationController中放置respond_to :html

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

If you do not use respond_with or want ActionView::MissingTemplate to be raised before the action is run (ie 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.

  • rails 4.2
  • responders 2.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM