How to set JSON / XML response headers in format.json / xml {render: json / xml => @ user.to_json / xml}?

I am using Ruby on Rails 3 and I am trying to set the JSON / XML response values.

In my controller I have

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

When I make an HTTP GET request for JSON / XML, it sets general values ​​like these

 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 

I would like to add / set header values ​​and add new parameters like message2 or header2 .

How to do it in the syntax format.json/xml { render :json/xml => @user.to_json/xml } ?

+4
source share
1 answer

The format.foo { render ... } object takes up a block. You can put where you want:

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

Source: https://habr.com/ru/post/1340361/


All Articles