formatをcsvにする(ブラウザからcsvを要求する)には
linkのurlの拡張子をcsvにする必要あり
フォーム
form.slim
.form
= form_tag 'output_csv.csv', method: :post do
.form-group
.mt10
= datetime_select :csv, :start_at
.mt10
= datetime_select :csv, :finish_at
.mt20.center
= submit_tag "Output CSV", class: 'btn btn-primary'
コントローラ
chat_csvs_controller.rb
def output_csv
start_at = datetime_params(params,'start_at')
finish_at = datetime_params(params,'finish_at')
csv_name = "chatbot#{start_at.strftime("%m/%d/%y")}to#{finish_at.strftime("%m/%d/%y")}.csv"
@chats = Chat.count_desc(start_at,finish_at)
respond_to do |format|
format.csv do
send_data render_to_string, filename: csv_name, type: :csv
end
end
end
モデル
chat.rb
class Chat < ActiveRecord::Base
scope :count_desc, -> start_at, finish_at {
Chat.select(:message,:created_at).where(created_at: start_at..finish_at).order('count_message desc').group(:message).count(:message)
}
end
ビュー
output_csv.csv.ruby
require 'csv'
CSV.generate do |csv|
column_names = %w(message count)
csv << column_names
@chats.each do |chat|
csv_column_values = [
chat[0],
chat[1]
]
csv << csv_column_values
end
end