Building Custom XML Responses in Rails

Assume you have a CitiesController with just one action capital_city, which doesn’t need any of the RESTful actions. I set up a custom route for this one action.

The capital_city action returns the xml like the following, for example:

<list>
  <item>Washington D.C.</item>
</list>

Here is what the entry in the routes.rb file looks like:

  get "cities/capital_city"

Your controller may look something like below, where call to City.capital_city is just a named scope defined in your model which takes a country name as an argument and returns the name of the capital city.

class CitiesController < ApplicationController
  
  # GET /cities/capital_city.xml?country=United States
  def capital_city
    @capital_city = City.capital_city(params[:country])
    
    respond_to do |format|
      format.xml # COMMENT THIS OUT TO USE YOUR CUSTOM XML RESPONSE INSTEAD  { render :xml => @capital_city }
    end
  end
end

Therefore, you need to create a xml builder file in place where you would normally expect the builder file to be, which is the view.
So, in this case, you would expect the builder file to be under views/cities/capital_city.xml.builder

Your views/cities/capital_city.xml.builder would contain:

xml.instruct!
xml.list do
  if @capital_city.empty?
    xml.item
  else
    xml.item @capital_city[0]['name']
  end
end

Then you should be able to hit http://localhost:3000cities/capital_city.xml?country=United States and see the xml response.

I recommend switching the HTTP method from ‘get’ to ‘post’ instead in the routes file, if for example, you are using the xml response for an AJAX request. However, for testing purposes it’s easier to use the get method first if you want to test it in your browser without special tools.

VN:F [1.9.22_1171]
Rating: 3.3/5 (4 votes cast)
VN:F [1.9.22_1171]
Rating: -1 (from 1 vote)
Building Custom XML Responses in Rails, 3.3 out of 5 based on 4 ratings
Facebook Twitter Email

Leave a Reply