Rails Routes - Limiting the available formats for a resource

后端 未结 6 1901
孤城傲影
孤城傲影 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:04

    None of the above solutions worked for me. I ended up going with this solution:

    post "/test/suggestions", to: "test#suggestions", :constraints => -> (req) { req.xhr? }
    

    Found on https://railsadventures.wordpress.com/2012/10/07/routing-only-ajax-requests-in-ror/#comment-375

    0 讨论(0)
  • 2020-11-30 09:12

    You just add constraints about format :

    resources :photos, :constraints => {:format => /(js|json)/}
    
    0 讨论(0)
  • 2020-11-30 09:15

    how about

    # routes.rb
    
    class OnlyAjaxRequest
      def matches?(request)
        request.xhr?
      end
    end
    
    post "/test/suggestions", to: "test#suggestions", :constraints => OnlyAjaxRequest.new
    

    it doesn't get to the controller at all. Taken from railsadventures

    0 讨论(0)
  • 2020-11-30 09:16

    If you need not only one or another than json (cant use #xhr?) I offer to you option below

    resource :offers, only: :show, format: true, constraints: { format: 'pdf' }

    Hope it helps

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-30 09:23

    You must wrap those routes in a scope. Constraints unfortunately don't work as expected in this case.

    This is an example of such a block...

    scope :format => true, :constraints => { :format => 'json' } do
      get '/bar' => "bar#index_with_json"
    end
    

    More information can be found here: https://github.com/rails/rails/issues/5548

    0 讨论(0)
提交回复
热议问题