30
loading...
This website collects cookies to deliver better user experience
https://example.com/export/leads.csv
and we start a download instead of rendering a normal page.config/routes.rb
file:get 'leads/export', to: 'leads#export'
export
because that makes it clear what this method is responsible for.app/controllers/leads_controller.rb
, let's create that.require 'csv'
class LeadsController < ApplicationController
def export
@leads = Leads.where(organization_id: current_user.organization_id)
respond_to do |format|
format.csv do
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = "attachment; filename=leads.csv"
end
end
end
end
export
method to do a few things here.@leads = Leads.where(organization_id: current_user.organization_id)
csv
library:require 'csv'
respond_to
method to allow controller endpoints to respond to multiple formats. You will see a lot of endpoints that respond with HTML, JSON, and even XML.respond_to do |format|
format.html
format.json { render json: @leads.to_json }
format.xml { render xml: @leads.to_xml }
end
format.csv
:respond_to do |format|
format.csv do
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = "attachment; filename=leads.csv"
render template: "path/to/index.csv.erb"
end
end
https://example.com/export/leads.csv
, the tailing leads.csv
extension tells our server to respond with the csv format.app/views/leads/export.csv.erb
. <%- headers = ['Email', 'Date'] -%>
<%= CSV.generate_line headers %>
<%- @leads.each do |lead| -%>
<%= CSV.generate_line([lead.data['email'], lead.created_at]) -%>
<%- end -%>
CSV.generate_line
to add a row.headers
, and store the headers of our CSV file.<%- headers = ['Email', 'Date'] -%>
<%= CSV.generate_line headers %>
<%- @leads.each do |lead| -%>
<%= CSV.generate_line([lead.data['email'], lead.created_at]) -%>
<%- end -%>
<a href="/leads/export.csv">Export CSV</a>
CSV.generate_line()
as many arguments as you want columns, and don't forget to pass headers in the first line to match!