Rails 3-限制资源路由中操作的格式 [英] Rails 3 - Restricting formats for action in resource routes

查看:78
本文介绍了Rails 3-限制资源路由中操作的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在路线中定义了一个资源。

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

对于json和xml。但是我不希望控制器响应html格式的请求。如何只允许json和xml?

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.

实现此目标的最佳方法是什么?
还有烘干Dry响应块的好技巧吗?

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

感谢您的帮助。

推荐答案

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

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' }

以上似乎迫使路由器向无格式请求提供服务显示动作,默认情况下为json。

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

这篇关于Rails 3-限制资源路由中操作的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆