【发布时间】:2016-10-17 06:31:58
【问题描述】:
在我的show 路由中,有一个my_search 路由(基本上是show#my_search)以HTML 格式显示数据的哈希数组。
我需要做的只是将@data 转储到我的render(或部分)并在视图中处理它们,使其成为一个嵌入了 ruby 的 HTML 表格。
但是,有没有一种简单的方法可以将相同的 @data 发送到 CSV 文件?我是否必须再次获得@data 并专门为它制作另一条路线?显示页面localhost://show/my_search时是否可以访问@data(最好是在下载其CSV或json渲染的链接中)?
编辑:
@data 看起来像:
@data = [ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ]
app/controllers/show_controller.rb 看起来像:
def my_search
@data = [ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ] # and other rows
# and do other stuff here
render "table_template"
在app/views/show/table_template.html 中看起来像:
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<% @data.each do |row| %>
<tr>
<td><%= row['name'] %></td>
<td><%= row['age'] %></td>
</tr>
<% end %>
</tbody>
</table>
2016 年 6 月 20 日更新:我目前的解决方法:
app/controllers/show_controller.rb:
def my_search
get_data
# and do other stuff here
render "table_template"
end
def my_search_export
get_data
format.each do |format|
# something that renders the CSV format when visiting localhost://my_search_export.csv
.....
end
end
private
def get_data # writes to @data
@data=[ {"name"=>"John", "age"=>"21"}, {"name"=>"Amy", "age"=>"20"} ]
end
在视图中:添加一个 url 到 localhost://my_search_export.csv。
不好的是它会再次加载数据,好的是工作流程很简单。我仍在寻找更好的解决方案。
附:这个网站可能有不同的用户同时运行,所以保留一个全局变量对我来说听起来不合适。
【问题讨论】:
-
谢谢Seth,但是当显示
localhost://show/my_search的网页时我如何输出CSV可下载链接 -
stackoverflow.com/questions/94502/… 可能会有所帮助——但这只会允许转到
localhosts://some/path/file.csv,这意味着它在localhosts://some/path/file.csv中没有显示网页
标签: ruby-on-rails ruby csv