Ruby on Rails如何将数据库中CSV导入数据渲染为HTML页面表格?
实现方案
第一步:替换Index页面代码
把你的app/views/hmrc_rates/index.html.erb文件替换为以下代码即可实现Excel风格的表格展示:
<h1>HmrcRates</h1> <%= link_to "Get Rates", new_hmrc_rate_path %> <!-- 表格部分代码 --> <table border="1" cellpadding="8" cellspacing="0" style="margin-top: 20px; border-collapse: collapse;"> <thead> <tr style="background-color: #f5f5f5;"> <th>序号</th> <th>国家/地区</th> <th>货币名称</th> <th>货币代码</th> <th>每英镑兑换单位</th> <th>生效起始日期</th> <th>生效结束日期</th> </tr> </thead> <tbody> <% if @hmrc_rates.any? %> <% @hmrc_rates.each_with_index do |rate, index| %> <tr> <td><%= index + 1 %></td> <td><%= rate.country %></td> <td><%= rate.currency %></td> <td><%= rate.curr_code %></td> <td><%= rate.units_per_pound %></td> <td><%= rate.start_date.strftime("%Y-%m-%d") if rate.start_date.present? %></td> <td><%= rate.end_date.strftime("%Y-%m-%d") if rate.end_date.present? %></td> </tr> <% end %> <% else %> <tr> <td colspan="7" style="text-align: center;">暂无汇率数据,请点击上方「Get Rates」按钮导入数据</td> </tr> <% end %> </tbody> </table>
代码说明
- 你在控制器index方法中已经查询了所有
HmrcRate表数据并存入@hmrc_rates实例变量,视图中可以直接调用该变量遍历渲染 - 代码里自带了简单的样式,
border-collapse: collapse可以实现Excel那种无缝的边框效果,日期格式化方法会把多余的时分秒隐藏,只保留年月日 - 加了空数据判断,未导入数据时会显示提示文字,不会出现空白表格
可选优化建议
- 你之前注释掉的
HmrcRate.create!(row.to_hash)报错的原因是CSV表头和你的模型字段名不一致,CSV的表头是带特殊符号的命名,和你迁移文件里定义的country、currency等字段名对应不上,你现在手动指定字段映射的写法是正确的 - 按照Rails的路由约定,
new动作默认是用来展示新建资源的表单,你现在把CSV导入逻辑写在new里功能可以正常跑,后续熟悉规范后可以单独定义一个import动作存放导入逻辑,更符合开发规范
内容的提问来源于stack exchange,提问作者Kvothe28
相关产品推荐
相关产品推荐

