WagnerMatosUK WagnerMatosUK - 15 days ago 5
Ruby Question

How to render xml in Rails 4

I'm having trouble rendering xml in a Rails app. I'm following the instructions from here and here's my controller:

...
respond_to do |format|
format.xml { render :xml => @cases }
end


In my view:

xml.instruct!
xml.cases do
@cases.each do |c|
xml.case do
xml.title c.case_number
end
end
end


Yet in my response all I'm getting is this:

<?xml version="1.0" encoding="UTF-8"?>
<nil-classes type="array"/>


I've never worked with xml in Rails before, so I'm bit confused. My controllers structure is like this:

app/controllers
app/controllers/shared
app/controllers/api


The controllers in
app/controllers/shared
is where I keep most of my logic, so in my
app/controllers/api
I reference the shared controllers like so:

class Api::CampaignsController < Shared::CampaignsController
protect_from_forgery with: :null_session
before_action :authenticate
end


Currently, my xml template is located here:
views/campaigns/method_in_my_controller.xml.builder
but I've had similar results (no data in the xml) when I had a view file here
views/shared/campaigns/method_in_my_controller.xml.builder


Wha am i missing?

Answer

Remove

respond_to do |format| 
    format.xml { render :xml => @cases } 
end 

And write

render :xml => @cases

You don't need view xml.builder. Remove it. Try to call @cases.to_xml in console. I know that to_xml works with hashes.

Comments