thanikkal
thanikkal

Reputation: 3356

Rails: return model (not bound to active record) as xml

I have a model class that is not bound to Active record.

  class ProcessingStatus
    attr_accessor :status, :timestamp
  end

The model acts as a processing status holder and will eventually be returned to the calling method.

Since this is invoked as an active resource method, this needs to go back (serialized) as xml. Here is my action method:

def activate
  @process_status = ProcessingStatus.new
  if Account.activate(params[:account])           
    @process_status.status = "success"
  else
    @process_status.status = "fail"
  end 
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @process_status }
  end
end

This doesn't seem to return a valid xml though.

If I try and output the @process_status like below

return render :text => "The object is #{@process_status}"

this is what I get:

The object is #<ProcessingStatus:0x00000005e98860>

Please tell me what I am missing.

Edit #1,

Based on the comment below, I modified my code to include the serialization libraries.

class ProcessingStatus 
  include ActiveModel::Serialization
  include ActiveModel::Serializers::JSON
  include ActiveModel::Serializers::Xml

  attr_accessor :status

  def attributes

    @attributes ||= {'status' => 'nil'}
  end
end

I am getting closer:) Now get the output as follows for .xml request. but the value that I assigned is not reflected.

@process_status.status = "success" / "fail"

<processing-status><status>nil</status></processing-status>

but when i make a json request, it is appearing correct!

{"processing_status":{"status":"success"}}

Upvotes: 0

Views: 348

Answers (1)

tjeden
tjeden

Reputation: 2079

You need to define method to_xml in your model, or include Serialization module as below:

class ProcessingStatus
  include ActiveModel::Serialization

  attr_accessor :status, :timestamp
end

Here you've got more info: http://api.rubyonrails.org/classes/ActiveModel/Serialization.html

Upvotes: 2

Related Questions