Skip to content

Reject invalid request types

Andreas Dausenau edited this page Jul 22, 2023 · 1 revision

Reject invalid request types

Ez-on-rails allows json and html request for EzOnRails::ResourceController and EzOnRails::ApplicationController actions and allows only json requests for EzOnRails::Api::ResourceController and EzOnRails::Api::BaseController.

But sometimes you want to have an action only available for one format, eg. if you want to have some additional ajax functionality in a resource controller. In that case you can make use of the methods json_request? and html_request? that are defined in the EzOnRails::ApplicationController controller. You can use them in a before action the following way:

class ArticlesController < EzOnRails::ResourceController
  ...
  before_action :invalid_request_type, unless: -> { json_request? }, only: [:tags]
  
  # GET /articles/:id/tags
  def tags
    ...
  end
  ...
end

This example disables html requests for the tags action in the articles controller. You can also use html_request? to disable json requests.

The invalid_request_type you are calling here is defined in the EzOnRails::ApplicationController raises an exception that returns a http status code 406 (not acceptable). Hence you do not have to implement any additional logic here. You just need to write the content of your needs in your action.

Clone this wiki locally