Rails 3:format.csv 给出“无模板错误”但 format.json 不需要模板
为什么它可以在没有模板的情况下渲染 :json,但不能渲染 :csv?
在我的 datapoints_controller 的索引方法中:
respond_to do |format|
format.json { render :json => @goal.datapoints.all }
format.csv { render :csv => @goal.datapoints.all }
end
将我的浏览器指向 /datapoints.json 会将集合呈现为屏幕上的 json 字符串。将其指向 /datapoints.csv 会出现错误:
Template Missing: with {:locale=>[:en, :en], :formats=>[:csv],
:handlers=>[:rhtml, :rxml, :erb, :builder, :rjs]}
Datapoint 的实例响应 to_csv,但即使我手动将其映射为 csv 格式并将其呈现为文本,它也会出现模板丢失错误,因此,例如我尝试了类似这样的操作:
format.csv { render @goal.datapoints.map{|d| d.to_csv }.join "\n" }
How come this works to render :json with no template, but not to render :csv?
in my datapoints_controller's index method:
respond_to do |format|
format.json { render :json => @goal.datapoints.all }
format.csv { render :csv => @goal.datapoints.all }
end
Pointing my browser to /datapoints.json renders the collection as a json string on screen. Pointing it to /datapoints.csv gives an error:
Template Missing: with {:locale=>[:en, :en], :formats=>[:csv],
:handlers=>[:rhtml, :rxml, :erb, :builder, :rjs]}
An instance of Datapoint responds to to_csv, but even if I manually map it into csv format and render it as text it gives a Template Missing error, so, e.g. I tried something like this:
format.csv { render @goal.datapoints.map{|d| d.to_csv }.join "\n" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Rails 附带了多种格式的渲染器,包括 json,但不包括 csv。 这是在 Rails 源代码中指定它们的位置 (查看底部是否有一系列
add
调用)。不过,创建自己的应用程序非常容易。将类似这样的内容放入初始化程序中(这几乎只是从上面链接的 xml 渲染器复制而来,其中 xml 替换为 csv)
: @foo 该块将被调用,并将
@foo
对象作为csv
参数传递。看看你在做什么,你可能需要猴子修补
Array
来添加to_csv
方法,或者让上面的块检测和处理数组。Rails comes with renderers for a bunch of formats, including json, but not csv. Here's where they are specified in the rails source (look towards the bottom for a series of
add
calls). It's pretty easy to create your own though.Put something like this into an initialiser (this is pretty much just copied from the xml renderer from the above link, with xml replaced with csv):
Then when you call
render :csv => @foo
this block will be called, with the@foo
object passed as thecsv
parameter.Looking at what your doing, you'll likely need to monkey patch
Array
to add ato_csv
method, or make the above block detect and handle arrays.