5 ruby xml rendering ruby-on-rails
我有一个ruby on rails应用程序,它有两个模型--ltests和sub_tests.ltest has_many与sub_tests 有"关联".在ltests的show方法如下.
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @ltest }
end
Run Code Online (Sandbox Code Playgroud)
这将呈现ltest对象.但是,属于ltest的sub_tests不会呈现.
我怎样才能做到这一点?
<ltest>
....
<sub_test>
...
</sub_test>
<sub_test>
...
</sub_test>
</ltest>
Run Code Online (Sandbox Code Playgroud)
我尝试使用这样的视图渲染它:
但这会生成两个xml文档,而不是嵌入在ltests中的sub_tests文档.
有关如何做到这一点的任何建议?
小智 14
您不必为此使用构建器或erb.您可以在控制器中获得您想要的内容(至少我可以在rails 2.3.4中),如下所示:
format.xml { render :xml => @ltest.to_xml(:include => :sub_tests) }
Run Code Online (Sandbox Code Playgroud)
小智 5
看起来,rails可以处理多个级别的嵌套.这是我最终得到的代码.
<%= @ltest.to_xml(:include => {
:test_group => { :include => [ :user ]},
:sub_tests => { :include => {
:attachments => {},
:errors => {},
:test_bugs => {},
} },
:attachments => {},
:errors => {},
:test_bugs => {},
:test_nodes => { :include => {
:node => { :include => [ :networks ]},
:attachments => {},
}}
} ) %>
Run Code Online (Sandbox Code Playgroud)
小智 1
在视图中执行此show.xml.erb操作就达到了目的。
<%= @ltest.to_xml :include => [ :sub_tests ]%>
Run Code Online (Sandbox Code Playgroud)
但是,嵌套在 sub_tests(test_logs、errors)内的对象被排除在外。
| 归档时间: |
|
| 查看次数: |
6192 次 |
| 最近记录: |