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

查看:20
本文介绍了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?这应该只发生在 show 动作中.

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.

实现这一目标的最佳方法是什么?还有什么好的技巧可以让 response_to 块变干?

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

以上似乎强制路由器为 show 操作提供无格式请求,默认为 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天全站免登陆