views:

946

answers:

4

I have a ruby on rails application which has two models - ltests and sub_tests. An ltest has a 'has_many' association with sub_tests. In the show method for ltests is as follows.

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @ltest }
end

This renders the ltest object. However the sub_tests belonging to the ltest don't render.

How can I do this?

<ltest>
....
   <sub_test>
   ...
   </sub_test>
   <sub_test>
   ...
   </sub_test>
</ltest>

I tried rendering it using a view like this: <%= @ltest.to_xml %> <%= @ltest.sub_tests.to_xml %>

But this generates two xml documents rather than one with sub_tests embedded in ltests.

Any suggestions on how I can do this?

+1  A: 

Doing this in the view show.xml.erb did the trick.

<%= @ltest.to_xml :include => [ :sub_tests ]%>

However, the objects nested inside sub_tests (test_logs, errors) get left out.

A: 

You should probably use xml builder to do this. http://www.xml.com/pub/a/2006/01/04/creating-xml-with-ruby-and-builder.html

Waseem
+1  A: 

Seems, rails can handle multiple levels of nesting. This is the code that I ended up with.

<%= @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 => {},
     }}
    } ) %>
+4  A: 

You don't have to use builder or erb for this. You can get what you want in the controller (at least I can in rails 2.3.4) like this:

format.xml  { render :xml => @ltest.to_xml(:include => :sub_tests) }
Buddy Brewer
Thanks... helped me tons!
fiXedd
Worth a doc link: http://api.rubyonrails.org/classes/ActiveRecord/XmlSerialization.html
fiXedd