Rails route for non-resource for csv
I have a method called "revisions", and I want to be able use the same logic but output to csv. I think I'd like to use the FasterCSV gem. What I need is to what to add to my routes in order to get a route for both the html and the cs开发者_如何学Cv outputs. I'd like my urls to be something like this:
invoices/51/revisions
invoices/51/revisions.csv
Thoughts?
Thanks much!
Rails makes this very easy. You don't need to change your routes at all to accommodate CSV format, since rails recognizes the csv MIME-type.
First, set up a route in routes.rb:
map.invoice_revisions 'invoices/:id/revisions.:format',
:controller=>:invoices,
:action=>:revisions
In your controller, do something like this:
def revisions
# ... set @revisions with something like
@revisions = Invoice.find(params[:id]).revisions
respond_to do |format|
format.html # will render the revisions html template
format.csv { render :csv => revisions_csv } # see sample method below
end
end
end
private
def revisions_csv # convert @revisions to csv: customize to your needs
FasterCSV.generate do |csv|
csv << @revisions.first.attributes.keys # set the headers
@revisions.each do |revision| # set the data
csv << revision.attributes.values
end
end
end
Here's a tutorial with more detailed info on formatting the csv files using csvbuilder:
http://rubyglasses.blogspot.com/2009/07/csv-views-with-fastercsv-and-csvbuilder.html
In your routes.rb:
resources :photos do get 'preview', :on => :member end
http://guides.rubyonrails.org/routing.html#adding-more-restful-actions
And in your controller, handle the format with a respond_to.
精彩评论