Rails 3 - Restricting formats for action in resource routes

有些话、适合烂在心里 提交于 2019-11-28 17:26:19

问题


I have a resource defined in my routes.

resources :categories

And I have the following in my Category controller:

  def show
    @category = Category.find(params[:id])

    respond_to do |format|
      format.json { render :json => @category }
      format.xml  { render :xml => @category }
    end
  end

The controller action works fine for json and xml. However I do NOT want the controller to respond to html format requests. How can I only allow json and xml? This should only happen in the show action.

What is the best way to achieve this? Also is there any good tips for DRYing up the respond_to block?

Thanks for your help.


回答1:


I found that this seemed to work (thanks to @Pan for pointing me in the right direction):

resources :categories, :except => [:show]
resources :categories, :only => [:show], :defaults => { :format => 'json' }

The above seems to force the router into serving a format-less request, to the show action, as json by default.




回答2:


You must wrap those routes in a scope if you want to restrict them to a specific format (e.g. html or json). 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

This answer is copied from my previous answer here..

Rails Routes - Limiting the available formats for a resource




回答3:


You could do the following in your routes.rb file to make sure that only the show action is constrained to json or xml:

resources :categories, :except => [:show]
resources :categories, :only => [:show], :constraints => {:format => /(json|xml)/}

If this doesn't work you could try explicitly matching the action:

resources :categories, :except => [:show]
match 'categories/:id.:format' => 'categories#show', :constraints => {:format => /(json|xml)/}



回答4:


constraints was not working for POST requests and then I tried defaults it works for all.

namespace :api, :defaults => { :format => 'json' } do
    namespace :v1 do
      resources :users do
        collection do
          get 'profile'
        end
      end
      post 'signup' => 'users#create'
      post 'login' => 'user_sessions#create'
  end
end

I was using Rails 4.2.7



来源:https://stackoverflow.com/questions/4997788/rails-3-restricting-formats-for-action-in-resource-routes

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