Idiomatic CSV export in Rails

Viewed 39

I have an index view of submissions and in the view I have @submissions the controller looks like this:

Submissions Controller

def index 
  @submissions = Submission.submissions_for(user: current_user)
end

From the view I want to essentially click a button and pass in that list of submissions

I've thought of adding a new route like so:

<%= link_to "Export", export_submissions_path(submissions: @submissions) %>

But that doesn't feel quite right because I need to stay on the index page. So when the user clicks the export button they stay on the index page but a CSV of the current data gets created. So, this questions is "how to create a CSV" it's more how do I stay on the index page and send a request to the server to send a CSV?

1 Answers

You can deliver different formats of a view from a single controller action.

class SubmissionsController < ApplicationController
  def index
    @submissions = Submission.submissions_for(user: current_user)

    respond_to do |format|
      format.html
      format.csv { send_data @submissions.to_csv, filename: "users-#{Date.today}.csv" }
  end
end

Then if you do the request with .csv it will deliver the csv instead of the view.

To get the right url use the url_helper as follows:

link_to 'CSV Export', submissions_path(format: :csv)
Related