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 5 years have passed since last update.

rails クエリを使って集計しcsvをexport

Posted at

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

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?