to_csv_rails
to_csv_rails implements a to_csv method on your Arrays. It makes exporting records to csv a simple task, even when using responders.
Installation
Simply add this to your Gemfile:
gem 'to_csv_rails'
Them run:
bundle install
Usage
Considering that you have a model called User. Here are some examples.
Exporting all fields
User.all.to_csv
Exporting only id and name
User.all.to_csv(:only => [:id, :name])
Exporting everything except id
User.all.to_csv(:except => [:id])
Adding headers
User.all.to_csv(:headers => [:id, :name])
Usage with responders
On a Rails application it's very common to use responders when you want to display the same data but with a different format.
Considering again that your model is User and that you have a controller called UsersController generated by scaffold. Change:
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
To:
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
format.csv { render csv: @users }
end
end
Accessing /users.csv will return your users in csv format.