Generating CSV files in Rails

CSV (Comma Separated Values) is a widely used file format to exchange data between different systems. In this blog post, we will learn how to generate CSV files in Rails. We will use the csv
library that comes bundled with Ruby to generate the CSV file.
Step 1: Create a controller
Let’s start by creating a new Rails controller. Open your terminal, navigate to your Rails application directory, and run the following command:
1
rails generate controller Products
This will create a new controller called ProductsController
and some basic files for the controller.
Step 2: Add a route
Now we need to add a route to our new controller. Open the config/routes.rb
file and add the following route:
1
get 'products/export_csv', to: 'products#export_csv'
This will create a new route that will be used to export the CSV data.
Step 3: Add an action to the controller
Next, we need to add an action to our controller that will generate the CSV file. Open the app/controllers/products_controller.rb
file and add the following code:
1
2
3
4
5
6
7
8
9
class ProductsController < ApplicationController
def export_csv
@products = Product.all
respond_to do |format|
format.csv { send_data @products.to_csv, filename: "products-#{Date.today}.csv" }
end
end
end
In this code, we are first fetching all the products from the database and then calling the to_csv
method on the collection to generate the CSV file. We are then using the send_data
method to send the generated CSV data as a file to the browser. The respond_to
block will check the requested format and respond accordingly.
Step 4: Add a to_csv
method to the model
Next, we need to define the to_csv
method on the Product
model. Open the app/models/product.rb
file and add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require 'csv'
class Product < ApplicationRecord
def self.to_csv
attributes = %w[id name description price created_at updated_at]
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |product|
csv << attributes.map { |attr| product.send(attr) }
end
end
end
end
In this code, we are first requiring the csv
library, and then defining the to_csv
method on the Product
model. In this method, we are defining the attributes we want to export to the CSV file. We then use the CSV.generate
method to generate the CSV file. In this block, we first define the headers for the CSV file and then iterate over all the products and add each row to the CSV file.
Step 5: Add a link to the view
Finally, we need to add a link to the view that will trigger the export action. Open the app/views/products/index.html.erb
file and add the following code:
1
<%= link_to 'Export CSV', products_export_csv_path(format: :csv) %>
This will create a link on the products/index
page that will export the CSV data when clicked.
That’s it! Now you should be able to export CSV data from your Rails application.