如何在不将数据存储在数据库或服务器上的情况下存储文件的内容

时间:2012-04-18 11:25:20

标签: ruby-on-rails ruby ruby-on-rails-3 forms ruby-on-rails-3.1

我只是希望表单读取.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对于这个

会是什么样子

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用tempfile:http://apidock.com/ruby/Tempfile