LoginSignup
0
1

More than 3 years have passed since last update.

【Rails】CSVエクスポート機能の実装

Posted at

目標

ezgif.com-video-to-gif.gif

開発環境

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

前提

下記実装済み。

Slim導入
Bootstrap3導入
投稿機能実装

実装

1.application.rbを編集

application.rb
require_relative 'boot'

require 'rails/all'
require 'csv' # 追記

Bundler.require(*Rails.groups)

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

2.コントローラーを編集

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

# 追記
def send_users_csv(books)
  csv_data = CSV.generate do |csv|
    header = %w(ID 登録日 投稿者 タイトル)
    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: '本一覧情報')
end

① CSVファイルのヘッダーを設定する。

header = %w(ID 登録日 投稿者 タイトル)
csv << header

② CSVファイルの内容を設定する。

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

③ CSVファイル名を設定する。

filename: '本一覧情報'

3.ビューを編集する。

books/index.html.slim
/ 追記
= link_to 'CSVエクスポート', books_path(format: :csv), class: 'btn btn-success'
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1