Collection2csv gem allows you to export a ActiveRecord collection of model objects to csv
Add this line to your application's Gemfile:
gem 'collection2csv'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install collection2csv
Use the collection_download helper like any other regular tag helper :
<%= collection_download(@activerecord_collection) %>
eg: <%= collection_download(@users) %>
In order to select a particular columns use column names as follows
<%= collection_download(@activerecord_collection, {columns: ['id','name']}) %>
eg: <%= collection_download(@users, {columns: ['id','name']}) %>
Download link text can be provided as follows
<%= collection_download(@activerecord_collection, {link_text: 'export'}) %>
eg: <%= collection_download(@users, {link_text: 'export'}) %>
Supports Associations
<%= collection_download(@activerecord_collection, {columns: ['id','name'], associations: {association_name: ['id','name']}}) %>
eg: <%= collection_download(@users, {columns: ['id','name'], associations: {book: ['name', 'author']}}) %>
Bug reports and pull requests are welcome on GitHub at https://github.com/ethirajsrinivasan/collection2csv.
The gem is available as open source under the terms of the MIT License.