我正在关注railscasts教程。我试图复制他们的一个教程,这个教程是关于将CSV和Excel文件导入到rails页面,但是我得到了循环依赖性错误。
尝试了以下解决方案但未解决问题:
请更多解决方案。提前谢谢。
查看: test.html.erb
<% provide(:title, 'CSV Import Test')%>
<div class="center hero-unit">
<h3> Test - CSV file import </h3>
</div>
<h4> Import .csv file </h4>
<%= form_tag import_products_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
<h4> Products </h4>
<table id="products">
<tr>
<th> Id </th>
<th> Tagnumber </th>
<th> IsEnabled </th>
</tr>
<% @products.each do |product| %>
<tr>
<td><%= product.id_pass %></td>
<td><%= product.tagnumber %></td>
<td><%= product.isenabled %></td>
</tr>
<% end %>
</table>
型号: product.rb
Class Product < ActiveRecord::Base
attr_accessible :id_pass, :tagnumber, :isenabled
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Product.create! row.to_hash
end
end
控制器: products_controller.rb
class ProductsController < ApplicationController
def test
@products = Product.order(:id_pass)
end
def import
Product.import(params[:file])
redirect_to root_url, notice: "Data imported."
end
end
配置: routes.rb
resources :products do
collection { post :import}
end
..
..
match '/test', to: 'products#test', via: 'get'
答案 0 :(得分:0)
好的,这些宝石真的很好用:
https://github.com/liangwenke/to_xls-rails
它们是非常简单的宝石,但它们可以非常快速地完成这项任务。我在这里写了一个清晰的rails 4教程:
https://github.com/liangwenke/to_xls-rails/wiki/Install%20Guide
您也可以按照作者的说明进行操作,但我发现它们很难。
在您的控制器中:
class ProductsController < ApplicationController
def test
@products = Product.order(:id_pass)
respond_to do |format|
format.xls { send_data(@posts.to_xls) }
# format.xls {
# filename = "products-#{Time.now.strftime("%Y%m%d%H%M%S")}.xls"
# send_data(@products.to_xls, :type => "application/excel; charset=utf-8; header=present", :filename => filename)
# }
end
end
end
在您看来:
<%= link_to "Excel", product_path(:format => :xls) %>