LoginSignup
0
0

More than 1 year has passed since last update.

家計簿アプリにCSV出力機能をつける

Posted at

個人開発で家計簿アプリを作ってみました。
どんな機能があったら便利かなーっと考えた時、ふとCSV出力機能を思いついたのでやってみました。
完成して一応動作するものが出来ましたが、本当にこれいるか?と少し疑問に思いつつも勉強にはなったので記録を残しておきたいと思います。
コードは以下の通り。

require 'csv'

 省略

def csv
  @records = Record.all.where(user_id: current_user.id).order(date: :desc)
  respond_to do |format|
    format.html
    format.csv do |csv|
      send_finance_csv(@records)
    end
  end
end

private

def send_finance_csv(records)
  csv_data = CSV.generate do |csv|
    column_names = %w(日付 金額 カテゴリー 収支)
    csv << column_names
    records.each do |record|
      if record.status == 1
        column_values = [
          record.date,
          record.price,
          record.genre.name,
          record.status = "支出",
        ]
      else
        column_values = [
          record.date,
          record.price,
          record.genre.name,
          record.status = "収入",
        ]
      end
      csv << column_values
    end
  end
  @user = current_user.name
  send_data(csv_data, filename: "#{@user}の家計簿.csv")
end

収入(1)と支出(2)をステータスというカラムで分けていました。
このままでは1,2で出力されてしまうので、ifで分岐しています。

  @user = current_user.name
  send_data(csv_data, filename: "#{@user}の家計簿.csv")

この部分で現在のユーザーを取得し、出力された時のファイルネームとしています。

0
0
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
0