Rails Routes - Limiting the available formats for a resource

♀尐吖头ヾ 提交于 2019-12-17 07:30:53

问题


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 to specify that only the JS format routes be created?


回答1:


You just add constraints about format :

resources :photos, :constraints => {:format => /(js|json)/}



回答2:


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




回答3:


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




回答4:


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




回答5:


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




回答6:


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



来源:https://stackoverflow.com/questions/3679200/rails-routes-limiting-the-available-formats-for-a-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!