0

我只想让表单读取 .csv 文件的内容而不将它们存储在任何地方并执行此操作

csv_text = File.read('thefiletheychoose') # If this line isnt possible can we store the contents of the csv temp somewhere?
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
  row = row.to_hash.with_indifferent_access
  Company.create!(row.to_hash.symbolize_keys)
end

我不知道 .html 会是什么样子

4

2 回答 2

1

考虑到您的表单中有一个文件上传字段:

<%= form_tag '/companies/create', :multipart => true do %>
  <label for="file">File to Upload</label>
  <%= file_field_tag "upload" %>
  <%= submit_tag %>
<% end %>

您应该在控制器中执行以下操作:

def create
  csv_text = params[:upload].read
  # Same thing as yours:
  csv = CSV.parse(csv_text, :headers => true)
  csv.each do |row|
    row = row.to_hash.with_indifferent_access
    Company.create!(row.to_hash.symbolize_keys)
  end
end
于 2012-04-18T11:44:45.910 回答
0

您可以使用临时文件:http: //apidock.com/ruby/Tempfile

于 2012-04-18T12:04:48.327 回答