Rails nested resources

I am trying to trick nested associations in Rails with ActiveResource. My example is as follows: I have an airport with many runways.

My show in airport controllers contains: @airport = Airport.find (params [: id])

When I call http: //localhost/airports/2.xml I get this XML snippet:

<airport>
  <code>DUS</code>
  <created-at type="datetime">2009-02-12T09:39:22Z</created-at>
  <id type="integer">2</id>
  <name>Duesseldorf</name>
  <updated-at type="datetime">2009-02-12T09:39:22Z</updated-at>
</airport>

      

Now I have changed the action to

@airport = Airport.find(params[:id], :include => :runways)

      

How can I achieve what the above download above the url gives me something like:

<airport>
  <code>FRA</code>
  <created-at type="datetime">2009-02-12T09:39:22Z</created-at>
  <id type="integer">2</id>
  <name>Frankfurt</name>
  <updated-at type="datetime">2009-02-12T09:39:22Z</updated-at>

  <runways>
    <runway>
      <id>1</id>
      <name>bumpy runway</name>
    </runway>
  </runways>

</airport>

      

And besides: if I have a client with

class Airport < ActiveResource::Base
  ..
end

      

and

class Runway < ActiveResource::Base
  ..
end

      

How can I get it to automatically load associations like:

a = Airport.find(1)
puts a.runways.length
=> 1

      

And (last but not least) there is a way to store data from the client, for example:

a = Airport.find(1)
a.runways << Runway.find(1)
a.save

      

Maybe I'm really too blind, but I'm stuck ... Any idea is appreciated.

thanks

Matt

+1


a source to share


2 answers


The parameter :include

to finder specifies that it should look forward to getting related items from the database. The option :include

for to_xml

indicates that it should be included in XML rendering.

If the canonical XML representation includes related objects, you can override the method to_xml

to make your life a little easier:

class Airport
  def to_xml(options={})
    super(options.merge(:include => :runways))
  end
end

      



and then, since it render

will call to_xml

if you don't, your controller code could just be

format.xml { render :xml => @airport }

      

+1


a source


I finally decided it myself. Didn't know to enable the inclusion in the statememt rendering:



def show
  @airport = Airport.find(params[:id], :include => :runways)
  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => @airport.to_xml(:include => :runways) }
  end
end

      

+2


a source







All Articles