[Ruby] [Rails] Implementation of CSV export function

less than 1 minute read

Target

ezgif.com-video-to-gif.gif

Development environment

・Ruby: 2.5.7 Rails: 5.2.4 ・Vagrant: 2.2.7 ・VirtualBox: 6.1 ・OS: macOS Catalina

Premise

Implemented below.

Slim introductionBootstrap3 installedPosting function implementation

Implementation

1. Edit application.rb

application.rb


require_relative'boot'

require'rails/all'
require'csv' # add

Bundler.require(*Rails.groups)

module Bookers2Debug
  class Application <Rails::Application
    config.load_defaults 5.2
  end
end

2. Edit the controller

books_controller.rb


def index
  @book = Book.new
  @books = Book.all
  # Addition
  respond_to do |format|
    format.html
    format.csv do |csv|
      send_users_csv(@books)
    end
  end
end

# Addition
def send_users_csv(books)
  csv_data = CSV.generate do |csv|
    header = %w (ID registration date poster title)
    csv << header
    books.each do |book|
      values = [book.id, book.created_at, book.user.name, book.title]
      csv << values
    end
  end
  send_data(csv_data, filename:'List information')
end

① Set the CSV file header.

header = %w (ID registration date poster title)
csv << header

② Set the contents of the CSV file.

books.each do |book|
  values = [book.id, book.created_at, book.user.name, book.title]
  csv << values
end

③ Set the CSV file name.

filename:'Book list information'

3. Edit the view.

slim:books/index.html.slim


/ Addendum
= link_to'CSV export', books_path(format: :csv), class:'btn btn-success'