154
147

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.

Rails4になってcsvが出力しやすくなった

Last updated at Posted at 2014-06-24

Railsでcsvファイル出力とか調べても model でCSV出力用のto_csvメソッド作ってcontorllerで respond_to format.csv して出力するようなのしかみつからんかった。
http://railscasts.com/episodes/362-exporting-csv-and-excel?language=ja&view=asciicast

user.rb
require 'csv'
class User < ActiveRecord::Base
  def self.to_csv
    CSV.generate do |csv|
      csv << column_names
      all.each do |model|
        csv << model.attributes.values_at(*column_names)
      end
    end
  end
end
user_controller.rb
def index
  respond_to do |format|
    format.html
    format.csv { send_data User.to_csv }
  end
end

でも csvとか出力の範疇だしそれわざわざ modelにもたせてごちゃごちゃさせるのやだし urlを扱おうとするとmodel に include Rails.application.routes.url_helpers とか書く必要も出てくるし死にたくなる。

Rails4から viewテンプレートとして .erb .haml .builder みたいな感じで .ruby 拡張子が使えるようになったのを利用して

show.csv.ruby
require 'csv'
CSV.generate do |csv|
  csv << column_names
  all.each do |model|
    csv << model.attributes.values_at(*column_names)
  end
end

みたいにview側にロジックを移してcsv整形してやれば出力をviewに統一できるしmodelに無茶させないので保守もしやすいし世界が平和になる

154
147
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
154
147

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?