2011-02-18 26 views
4

我正在使用Ruby on Rails 3,並試圖設置JSON/XML響應的值。如何在'format.json/xml {render:json/xml => @ user.to_json/xml}'中設置JSON/XML響應的標題?

在我的控制器我有

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

當我爲JSON/XML HTTP GET請求,它被設置共同的價值觀像這些

header: 
    date: 
    - Fri, 18 Feb 2011 18:02:55 GMT 
    server: 
    - Apache ... 
    etag: 
    - "\"0dbfd0ec23934921144bd57d383db443\"" 
    cache-control: 
    - max-age=0, private, must-revalidate 
    x-ua-compatible: 
    - IE=Edge 
    x-runtime: 
    - "0.033209" 
    status: 
    - "200" 
    transfer-encoding: 
    - chunked 
    content-type: 
    - application/json; charset=utf-8 #or application/xml; charset=utf-8 
http_version: "1.1" 
message: OK 
read: true 

我想添加/套header值並添加新參數,如message2header2

如何在format.json/xml { render :json/xml => @user.to_json/xml }語法中做到這一點?

回答

8

format.foo { render ... }東西擋住了。你可以放任何你想要的東西:

format.json do 
    response['X-Message-1'] = 'Hello' 
    render :json => @user.to_json 
end