Rails 3 - 限制资源路由中的操作格式

Mik*_*ike 36 ruby resources routes dry ruby-on-rails-3

我的路线中定义了资源.

resources :categories
Run Code Online (Sandbox Code Playgroud)

我的类别控制器中有以下内容:

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

    respond_to do |format|
      format.json { render :json => @category }
      format.xml  { render :xml => @category }
    end
  end
Run Code Online (Sandbox Code Playgroud)

控制器动作适用于json和xml.但是,我不希望控制器响应html格式请求.我怎么才能只允许json和xml?这应该只在show动作中发生.

实现这一目标的最佳方法是什么?还有什么好的提示来干掉respond_to块吗?

谢谢你的帮助.

Mik*_*ike 41

我发现这似乎有效(感谢@Pan指出我正确的方向):

resources :categories, :except => [:show]
resources :categories, :only => [:show], :defaults => { :format => 'json' }
Run Code Online (Sandbox Code Playgroud)

以上似乎强制路由器默认为json,为show动作提供无格式请求.

  • 如果将.html扩展名添加到网址,则仍会使用html模板进行响应. (3认同)

koo*_*nse 36

如果要将这些路由限制为特定格式(例如html或json),则必须将这些路由包装在作用域中.遗憾的是,在这种情况下,约束条件无法正常工作.

这是这样一个块的一个例子......

scope :format => true, :constraints => { :format => 'json' } do
  get '/bar' => "bar#index_with_json"
end
Run Code Online (Sandbox Code Playgroud)

更多信息可以在这里找到:https://github.com/rails/rails/issues/5548

这个答案是从我之前的答案复制而来的.

Rails Routes - 限制资源的可用格式

  • 谢谢,这是非常有用的答案.为我工作就像一个魅力. (4认同)
  • 这在导轨4.2中按预期工作,谢谢 (2认同)

Pan*_*kos 24

您可以在routes.rb文件中执行以下操作,以确保只将show动作约束为json或xml:

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

如果这不起作用,您可以尝试显式匹配操作:

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

  • 对不起,这似乎不起作用.请求html页面仍然响应. (2认同)