I have a rails application in which most of the actions respond to json.

Is there any "switch" I can turn off to prevent all the controllers from responding to json despite the respond_to method call, or I still have to disable it manually in every action (which seems very odd).

有帮助吗?

解决方案

I have a proposal, though a bit hacky I'm afraid :)

class < ApplicationController
  before_filter :disable_json

  def disable_json
    if request.format =~ /json/
      //do something you like, redirect_to or reply with message
    end
  end

The before_filter will be fired before any specific controller's method.

The json header is usually "application/json"

For request, you can read more here: http://guides.rubyonrails.org/action_controller_overview.html#the-request-object

其他提示

You can also do it in routes.rb, using constraints:

# Only allow HTML requests for all resources within the block
scope constraints: {format: :html} do
  resources :posts
  resources :comments
  get "/profile", to: "users#profile"
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top