README.rdoc in csv_rails-0.4.1 vs README.rdoc in csv_rails-0.5.0

- old
+ new

@@ -19,21 +19,65 @@ @users = User.all respond_to do |format| format.html { @users = @users.all } format.json { render json: @users } - format.csv{ render csv: @users, :fields => [:id, :name, :age], :encoding => 'SJIS' } + format.csv{ render csv: @users, fields: [:id, :name, :age], encoding: 'SJIS', without_header: true } end end == Usage -If you want formatted created_at in the csv you should write like this +If you want formatted attribute, CsvRails call "#{attribute}_as_csv". For example, you wish formatted created_at then you write like this. class User < ActiveRecord::Base def created_at_as_csv created_at.strftime("%F %H:%M") end end - + +CsvRails define a singleton method Array.to_csv, and the method accept fields option. The fields option can not only database fields also method and method chain. + + class User < ActiveRecord::Base + has_many :memberships + has_many :groups, through: :memberships + + def ok + "OK" + end + end + + class UsersController < ApplicationController + def index + @users = User.all + + respond_to do |format| + format.csv{ render csv: @users, fields: [:ok, :"groups.first.name"], encoding: 'SJIS' } + end + end + +If you do not use :header option, header is using :fields and I18n transfer. + # config/locales/ja.yml + ja: + activerecord: + attributes: + group: &groupmodel + name: グループ名 + user: + id: ID + name: 名前 + age: 年齢 + ok: OK + groups: + first: + <<: *groupmodel + + # app/controllers/user_controller.rb + def index + @users = User.where("id < 1").all + respond_to do |format| + format.csv{ render csv: @users, fields: [:ok, :"groups.first.name"], encoding: 'SJIS' } #=> "OK,グループ名" + end + end + Copyright (c) 2012 yalab, released under the MIT license