【发布时间】:2011-02-11 20:26:16
【问题描述】:
当我为我拥有的多态关联使用 :include 子句呈现 XML 时,它不起作用。我最终得到返回对象指针而不是实际对象的 XML,例如:
<posts>
#<Comment:0x102ed1540>#<Comment:0x102ecaa38>#<Comment:0x102ec7fe0>#<Comment:0x102ec3cd8>
</posts>
然而 as_json 有效!当我使用 :include 子句呈现 JSON 时,关联被正确呈现,我得到如下内容:
posts":[
{"type":"Comment","created_at":"2010-04-20T23:02:30-07:00","id":7,"content":"fourth comment"},
{"type":"Comment","created_at":"2010-04-20T23:02:26-07:00","id":6,"content":"third comment"}]
我目前的解决方法是使用 XML 构建器,但从长远来看,我对此不太满意。有没有人碰巧知道这个问题?我有点在 catch-22 中,因为虽然 XML 不呈现关联,但 as_json 不会以 kosher json 格式呈现(返回一个数组而不是正确的 json 应该的哈希列表)和反序列化器 I' m 在客户端使用需要修改才能正确解析 json。
edit我正在使用 2.3.5 - 我也在使用 has_many_polymorphs gem 来表示多态有很多:通过,这可能会导致问题...
模型是我有环聊,每个环聊都有很多帖子,多态为cmets、照片等。
XML 的控制器代码: format.xml { 渲染 :xml => @hangouts.to_xml(:include => :users , :methods => :posts) }
json 的代码类似(在模型中): def as_json(选项) super(:include => :users, :methods => :posts)
【问题讨论】:
-
你使用的是什么 Rails 版本?
-
jpartogi,bensie:我正在使用 2.3.5 - 我也在使用 has_many_polymorphs gem 进行多态有很多:通过,这可能会导致问题...模型是我有视频群聊,并且每个视频群聊都有许多帖子,这些帖子与 cmets、照片等具有多态性。 XML 的控制器代码:format.xml { render :xml => @hangouts.to_xml(:include => :users , :methods => :posts) json 的代码类似(在模型中): def as_json(options) super(:include => :users, :methods => :posts)
-
此外,我可以绕过 has_many_polymorphs 并定义 :cmets, :photos 方法以包含在 to_xml 中 - 虽然 hangout.cmets 和 hangout.photos 在控制台中工作正常,但 xml 仍然返回对象点。奇怪...
标签: ruby-on-rails