(...) # 検索条件 records = Company.where(condition) respond_to do |format| format.html format.csv do send_data records end end end end (app/models/company.rb) require 'csv' class Company < ApplicationRecord def to_csv(condition) csv = CSV.generate(:force_quotes => true) { |csv| csv << @records.first.keys @records.each do |r| csv << r end } csv.encode('Shift_JIS', undef: :replace) end end (app/controllers/company_controller.rb) class CompanyController < ApplicationController def index condition = (...) # 検索条件 @records = Company.where(condition) respond_to do |format| format.html format.csv do send_data render_to_string end end end end (app/views/company/index.csv.ruby) require 'csv' csv = CSV.generate(:force_quotes => true) { |csv| csv << @records.first.keys @records.each do |r| csv << r end } csv.encode('Shift_JIS', undef: :replace) Viewで実装 view 拡張子に .ruby を指定して ruby コードを記述 処理 ロジック自体 同じように書ける