Rails:以 xml 形式返回模型(未绑定到活动记录)
我有一个未绑定到活动记录的模型类。
class ProcessingStatus
attr_accessor :status, :timestamp
end
该模型充当处理状态持有者,最终将返回到调用方法。
由于这是作为活动资源方法调用的,因此需要返回(序列化)为 xml。 这是我的操作方法:
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
但这似乎没有返回有效的 xml。
如果我尝试输出如下所示的 @process_status
,
return render :text => "The object is #{@process_status}"
这就是我得到的:
该对象是#
请告诉我我缺少什么。
编辑#1,
根据下面的评论,我修改了代码以包含序列化库。
class ProcessingStatus
include ActiveModel::Serialization
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
attr_accessor :status
def attributes
@attributes ||= {'status' => 'nil'}
end
end
我越来越接近了:) 现在获取 .xml 请求的输出,如下所示。 但我分配的值没有反映出来。
@process_status.status = "success" / "fail"
<processing-status><status>nil</status></processing-status>
但是当我发出 json 请求时,它看起来是正确的!
{"processing_status":{"status":"success"}}
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"}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在模型中定义方法
to_xml
,或包含序列化模块,如下所示:在这里您可以获得更多信息:http://api.rubyonrails.org/classes/ActiveModel/Serialization.html
You need to define method
to_xml
in your model, or include Serialization module as below:Here you've got more info: http://api.rubyonrails.org/classes/ActiveModel/Serialization.html