Ask A Question


You’re not receiving notifications from this thread.

How do I create two buttons that generate CSV files with different attributes?

Steve asked in Rails


I have two questions: 1) I would like to create a button that can generate a CSV file with one set of attributes, and another button that will be able to generate a different set of attributes.

2) Is it possible to add a feature where the CSV file will auto-populate an attribute(or heading) with line-items filled in. For example, when I generate the CSV file I want the sales_tax heading with a code "S" auto-populated in it.

I was able to follow the "Import and Export CSV file" series successfully, but it didn't have this feature I'm looking for.

Thanks in advance.


class UsersController < ApplicationController
  def index
    @users = User.all

    respond_to do |format|
      format.csv { send_data @users.to_csv, filename: "users-#{}.csv" }
    class User < ApplicationRecord
  def self.to_csv
    attributes = %w{id email name price quantity sales_tax total_amount }

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |user|
        csv << user.attributes.values_at(*attributes)

views section
<%= link_to 'csv1', users_path(format: "csv") %>

<%= link_to 'csv2', users_path(format: "csv") %>

Regarding question 1: Just add a custom parameter to your paths, like that:

<%= link_to 'csv1', users_path(format: "csv", set: 1) %>
<%= link_to 'csv2', users_path(format: "csv", set: 2) %>

You'll be able to receive this parameter from your controller (like an ordinary parameter: params[:set]), and use it to decide hov to populate your CSVs.


Alex's suggestion for #1 is exactly the right way to approach that.

For #2, I'm not quite sure I'm following. Are you wanting the sales_tax header to be just "S" or do you want each of the rows to have "S" as the value for the sales tax column or something else?


I appreciate the response guys. Yes, I would like each row to have an S auto populated.

I'm very new at programming so just bare with me. Would I need to create two def methods with each params[:set]? like this?

  def download_csv
    respond_to do |format|
      format.csv { send_data Post.all_entries_csv(params[:set2]) }

Many thanks guys!

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 79,047+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.