0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RailsでCSV出力をviewに任せる実装

Last updated at Posted at 2021-05-07

ほぼほぼこちらの記事の通りなのですが、自分でいろいろ試行錯誤する部分があったので自分用にメモ
https://qiita.com/ichi_s/items/eddf29d62ac09f6f9133

rails new などは割愛しますがCSV用の出力のコントローラーを作成しエクスポート用のアクションを以下のように用意します

csv_export_controller.rb
class CsvExportController < ApplicationAdminController
  def index
    # index用のなにかしらの処理 
  end
  def export
    # Viewに渡すデータを用意
    @users = Users.all
    
    # csvの中身の組み立てはviewで行います
    send_data(render_to_string(template: 'csv_export/export.csv.ruby', type: 'text/csv', filename: 'export_csv.csv'))
  end
end
views/export_csv/export.csv.ruby
#require 'csv' # Gemを使いましょう

# 出力に使うメソッドを定義すると呼び出せます(ヘルパーやデコレーターに書きましょう)
def user_nameuser
  user.last_name + user.last_name
end

header = %w(
    名前
    住所
    電話番号
    メールアドレス
  )

# 実際の処理
CSV.generate(headers: header, write_headers: true) do |csv|
  @users.find_each do |user|
    row = []
    row << user_name(user)
    row << user.address
    row << user.tel
    row << user.mail

    csv << row
    # sjisで出す場合、安全な文字に変換しとくと安心
    # https://qiita.com/cog1t0/items/263ab21a25e2cbd2ecc7
  end
end

# sjis
# csv_data = CSV.generate(~) o
# csv_data = csv_cata.encode(Encodinf::SJIS, { :invalid => :replace, :undef => :replace, :replace => ""}

Railsに慣れきってると、シンプルなrubyファイルに書くの戸惑いますね(笑)

0
0
3

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?