Search code examples
xmlruby-on-rails-3respond-with

Rails controller processing as HTML instead of XML


I've recently upgraded from Ruby 1.8.6 and Rails 2.3.4 to Ruby 1.9 and Rails 3.0.3.

I have the following controller:

class ChartController < ApplicationController

  before_filter :login_required

  respond_to :html, :xml  

  def load_progress  

    chart.add( :series, "Memorized",  y_memorized )
    chart.add( :series, "Learning",   y_learning  )
    chart.add( :series, "Mins / Day", y_time      )  
    chart.add( :user_data, :secondary_y_interval, time_axis_interval )

    respond_to do |fmt|
      fmt.xml { render :xml => chart.to_xml }
    end

    # Also tried
    # respond_with chart

  end   
end

However, when I call the 'load_progress method' I get the following:

Started GET "/load_progress.xml" for 127.0.0. Processing by ChartController#load_progress as HTML Completed 406 Not Acceptable in 251ms

I have also tried changing the respond_to block to

respond_with chart

But I get the same response. I've read all the new Rails documentation on the new respond_with format but I can't seem to elicit an XML response. Am desperately hoping someone has some ideas.


Solution

  • I had the same issue, and the following snippet worked for me:

      respond_to :xml
      def list
        @items = Item.all
        render :xml => @items
      end
    

    406 can happen for several reasons - usually when one uses wrong MIME types -, but based on the rails guides when you create an XML response as described above, everything will be filled out correctly by rails.

    There is one disadvantage of the above snippet. It will list every attribute of your model.

    In your example I'm not sure whether the chart variable is initialized/visible or not.