28
29

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.

Ruby1.9とRailsでCSV出力(SJIS)

Last updated at Posted at 2012-04-02

Usersテーブルの中身をすべてCSVで書き出す例

UserModel < ActiveModel::Base
  def self.csv
    require 'tempfile'
    require 'csv'

    csv_string = CSV.generate do |csv|
      csv << ['グループID','名前','メールアドレス']
      self.all.each do |m|
        csv << [m.group_id, m.name, m.email]
      end
    end
    csv_file = Tempfile.new('download', :encoding => Encoding::CP932)
    csv_file.puts csv_string
    csv_file.close
    csv_file.path
  end
end

User.csv #=> csv出力されたファイルのパス名
28
29
3

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
28
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?