views:

94

answers:

1

Hello,

Can someone provide an example of using Builder to create multiple XML files from a SQL database. I can easily create one containing the entire database as in here...

def index
  respond_to do |format|
   format.xml { @rides = Rides.find(:all) }
  end
end

This will create a file called index.xml based on a file I created called index.xml.builder which contains the following code

xml.instruct!
xml.rides do
@rides.each do |ride|
  xml.item("togive" => ride.togive, "totake" => ride.totake, "howlong" => ride.howlong,       "isoffer" => ride.isoffer, "id" => ride.id, "contact" => ride.contact)
 end
end

Here are the only lines in my routes.rb

map.resources :rides
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

This works fine, but how would I create a new file that contains the last element in Rides?

Thanks

edit: changed from format.rss to format.xml

+1  A: 

I'm not entirely sure what you're trying to achieve, but you could have another method in your controller that returns the last ride:

def last
  respond_to do |format| 
    format.xml { @last_ride = Rides.last } 
  end 
end

And then in the view template last.xml.builder you could have something like:

xml.instruct! 
xml.rides do 
  xml.item("togive" => @last_ride.togive, "totake" => @last_ride.totake etc...) 
end

If you went with this approach then you'd need to modify your config/routes.rb file to add a new collection route for the list action:

map.resources :rides, :collection => { :last => :get }

Alternatively you could simply make the find call within the controller's index method conditional so that it fetches all rides or the last ride as appropriate. In this case you should be able to re-use the existing index.xml.builder view template because it will just output a collection that happens to only ever contain one ride.

John Topley
Yes this is exactly what I am trying to do. It should work, but It can never find the route for it. So this would then be accessible via the web from say http://something:3000/latest or http://something:3000/rides/latest ??
Pat R
It depends what your `config/routes.rb` file looks like. Can you edit your question to include the contents of it please.
John Topley
I'm guessing I need to add another line to routes.rb in order to it to recognize the latest method in the controller?
Pat R
Also when i go to rides/latest i get the following error.... Unknown action No action responded to show. Actions: create, index, latest, and new
Pat R
I've updated my answer to include the routing code you need.
John Topley
Excellent thank you for your help! I knew it was probably just a routes problem...
Pat R
You’re welcome!
John Topley