RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12214

Can I respond with XML to an HTML request in Rails?

I want to put in a simple API that responds to a GET request with a query string. But I want to return XML, not HTML.

I would even like to test this in the browser so that if I key in the URL and the query string, then see the XML in the response.

I just about have it by rendering :text, but my xml is doing two things:

1. All tag names are being downcased.

2. My xml is being wrapped in an HTML container (HTML, HEAD, BODY, etc.)

I just need to get rid of that HTML wrapper.

Upvotes: 0

Views: 2983

Answers (4)

Guillermo Siliceo Trueba
Guillermo Siliceo Trueba

Reputation: 4609

On rails 5.2.x this is how you do it

class UserController < ApplicationController
  def view
    @user = User.find(params[:id])
    render formats: [:xml]
  end
end

With its corresponding view on app/views/user/view.xml

xml.User do
  xml.name @user.name
end

Upvotes: 0

catcon
catcon

Reputation: 50

layout false, only: [:action]

This will remove all layout associated code.

Upvotes: 0

thorsten m&#252;ller
thorsten m&#252;ller

Reputation: 5651

This one works for me:

respond_to do |format|
  format.xml do
    headers['Content-Disposition'] = 'attachment;filename="katalog.xml"'
    render :xml => xml_array.to_xml(:skip_types => true, :root => "Items"),
           :layout => false,
           :content_type => Mime::XML
  end
end

You should be able to replace xml_array.to_xml(:skip_types => true, :root => "Items") with your string, since .to_xml doesn't do anything else but generating a string (and making sure it's proper XML)

Upvotes: 2

Oktav
Oktav

Reputation: 2151

You could simply render as xml (in your controller) with:

render xml: @your_object

Upvotes: 1

Related Questions