rails 3: format.csv gives "no template error" but format.json needs no template -
how come works render :json no template, not render :csv?
in datapoints_controller's index method:
respond_to |format| format.json { render :json => @goal.datapoints.all } format.csv { render :csv => @goal.datapoints.all } end
pointing browser /datapoints.json renders collection json string on screen. pointing /datapoints.csv gives error:
template missing: {:locale=>[:en, :en], :formats=>[:csv], :handlers=>[:rhtml, :rxml, :erb, :builder, :rjs]}
an instance of datapoint responds to_csv, if manually map csv format , render text gives template missing error, so, e.g. tried this:
format.csv { render @goal.datapoints.map{|d| d.to_csv }.join "\n" }
rails comes renderers bunch of formats, including json, not csv. here's specified in rails source (look towards bottom series of add
calls). it's pretty easy create own though.
put initialiser (this pretty copied xml renderer above link, xml replaced csv):
actioncontroller::renderers.add :csv |csv, options| self.content_type ||= mime::csv self.response_body = csv.respond_to?(:to_csv) ? csv.to_csv : csv end
then when call render :csv => @foo
block called, @foo
object passed csv
parameter.
looking @ doing, you'll need monkey patch array
add to_csv
method, or make above block detect , handle arrays.
Comments
Post a Comment