Rails 3 respond_to:默认格式? [英] Rails 3 respond_to: default format?

查看:35
本文介绍了Rails 3 respond_to:默认格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Rails 2 应用程序转换为 Rails 3.我目前有一个控制器设置如下:

I am converting a Rails 2 application to Rails 3. I currently have a controller set up like the following:

class Api::RegionsController < ApplicationController
  respond_to :xml, :json
end

with 和一个如下所示的操作:

with and an action that looks like the following:

def index
  @regions = Region.all

  respond_with @regions  
end

实现非常简单,api/regions、api/regions.xml 和 api/regions.json 都按您的预期响应.问题是我希望 api/regions 默认通过 XML 响应.我有消费者希望得到 XML 响应,除非绝对必要,否则我不想让他们更改所有 URL 以包含 .xml.

The implementation is pretty straightforward, api/regions, api/regions.xml and api/regions.json all respond as you would expect. The problem is that I want api/regions by default to respond via XML. I have consumers that expect an XML response and I would hate to have them change all their URLs to include .xml unless absolutely necessary.

在 Rails 2 中,您可以这样做:

In Rails 2 you would accomplish that by doing this:

respond_to do |format|
  format.xml { render :xml => @region.to_xml }
  format.json { render :json => @region.to_json }
end

但在 Rails 3 中,我找不到将其默认为 XML 响应的方法.有什么想法吗?

But in Rails 3 I cannot find a way to default it to an XML response. Any ideas?

推荐答案

如果我理解您要做什么,您可能可以通过将默认资源格式设置为 XML 来解决问题.这将允许您的用户使用api/regions"发出请求,并将响应默认为 XML.查看控制器命名空间和路由"和定义默认值"部分:

If I understand what you are trying to do, you probably can solve the issue by setting the default resource format to XML. This will allow your users to make requests using 'api/regions' and have the response default to XML. Take a look at look at the 'Controller Namespaces and Routing' and the 'Defining Defaults' sections at:

http://guides.rubyonrails.org/routing.html

您可以在 routes.rb 中执行以下操作:

You could do something like the following in routes.rb:

namespace "api" do
  resources :regions, :defaults => { :format => 'xml' }
end

那么你应该能够为你的控制器方法做以下工作:

Then you should be able to have the following work for your controller methods:

class Api::RegionsController < ApplicationController
  respond_to :xml, :json

  def index 
    respond_with(@regions = Region.all)
  end
end

这篇关于Rails 3 respond_to:默认格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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