Rails Routes - Limiting the available formats for a resource

后端 未结 6 1910
孤城傲影
孤城傲影 2020-11-30 08:31

I have a series of resources that I want only available if accessed via the JS format. Rails\' route resources gives me the formats plus the standard HTML. Is there a way

6条回答
  •  感情败类
    2020-11-30 09:18

    You can use a before_filter that raises a routing error unless the request format is MIME::JS.

    app/controllers/application_controller.rb:

    class ApplicationController < ActionController::Base
      before_filter :check_js
    
      private
        def check_js
          raise RoutingError.new('expected application/json') unless request.format == MIME::JS
        end
    end
    

    Apply this filter more surgically with :only, :except, and :skip_before_filter as covered in the rails Action Controller Guide

提交回复
热议问题