首页 文章

Rails无法呈现XML的多态关联?

提问于
浏览
0

当我使用: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不以犹太json格式呈现(返回数组而不是正确的json应该的哈希列表)和反序列化器I'在客户端使用m将需要修改才能正确解析json .

edit 我正在使用2.3.5 - 我也使用has_many_polymorphs gem为多态有很多:通过,这可能会导致问题...

模型是我有环聊,每个环聊都有很多帖子,这些帖子对评论,照片等都是多态的 .

XML的控制器代码:format.xml {render:xml => @ hangouts.to_xml(:include =>:users,:methods =>:posts)}

json的代码类似(在模型中):def as_json(options)super(:include =>:users,:methods =>:posts)

2 回答

  • 0

    从Objective Resource google groups看来,这似乎是Rails中不存在的一项功能,所以我最后只使用了XML builder

  • 0

    我可以让这一行返回完整的嵌套XML

    format.xml { render :xml => @post.to_xml(:include => [ :links, :assets])}
    

    喜欢

    <?xml version="1.0" encoding="UTF-8"?>
    <post>
      <body>testing.../body>
      <created-at type="datetime">2010-09-21T06:19:13Z</created-at>
      <id type="integer">1</id>
      <title>1</title>
      <updated-at type="datetime">2010-09-21T06:19:13Z</updated-at>
    
      <links type="array"/>
      <assets type="array">
        <asset>
          <attachable-id type="integer">1</attachable-id>
          <attachable-type>Post</attachable-type>
          <created-at type="datetime">2010-09-21T06:19:13Z</created-at>
          <data-content-type>image/jpeg</data-content-type>
    
          <data-file-name>IMG00017-20100906-1226.jpg</data-file-name>
          <data-file-size type="integer">0</data-file-size>
          <id type="integer">1</id>
          <updated-at type="datetime">2010-09-21T06:19:13Z</updated-at>
        </asset>
      </assets>
    </post>
    

    这是我们的模型

    class Post < ActiveRecord::Base
      has_many    :assets, :as => :attachable, :dependent => :destroy
      has_many    :links, :as => :linkable, :dependent => :destroy
    ...
    

    链接模型

    class Link < ActiveRecord::Base
      belongs_to :linkable, :polymorphic => true
    ...
    

    资产模型

    class Asset < ActiveRecord::Base
     belongs_to :attachable, :polymorphic => true
    ...
    

    在这里,资产和链接不受任何特定模型的约束 . 在当前用法中,它们用于Post . 稍后其他型号可以使用它们 .

    那是你想要实现的目标吗?

相关问题