Generate multiple XML files based on database
Can someone provide an example of using Builder to create mul开发者_开发知识库tiple 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
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 }
- This would then let you access the route using http://localhost:3000/rides/last.xml
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.
精彩评论