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
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
You just add constraints about format :
resources :photos, :constraints => {:format => /(js|json)/}
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
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
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
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