ruby-on-rails – 如何在RoR中上传文本文件并将内容解析到数据库中

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何在RoR中上传文本文件并将内容解析到数据库中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
到目前为止,我已设法上传文件
  1. # In new.html.erb
  2. <%= file_field_tag 'upload[file]' %>

并访问控制器中的文件

  1. # In controller#create
  2. @text = params[:upload][:file]

但是,这只给出了文件名,而不是文件内容.我如何访问其内容

我知道这是一个跳转,但是一旦我可以访问文件内容,是否可以上传文件夹并遍历文件

解决方法

完整的例子

例如,上传包含联系人的导入文件.您不需要存储此导入文件,只需处理它并将其丢弃即可.

路线

的routes.rb

  1. resources :contacts do
  2. collection do
  3. get 'import/new',to: :new_import # import_new_contacts_path
  4.  
  5. post :import # import_contacts_path
  6. end
  7. end

形成

意见/联系人/ new_import.html.erb

  1. <%= form_for @contacts,url: import_contacts_path,html: { multipart: true } do |f| %>
  2.  
  3. <%= f.file_field :import_file %>
  4.  
  5. <% end %>

调节器

控制器/ contacts_controller.rb

  1. def new_import
  2. end
  3.  
  4. def import
  5. begin
  6. Contact.import( params[:contacts][:import_file] )
  7.  
  8. flash[:success] = "<strong>Contacts Imported!</strong>"
  9.  
  10. redirect_to contacts_path
  11.  
  12. rescue => exception
  13. flash[:error] = "There was a problem importing that contacts file.<br>
  14. <strong>#{exception.message}</strong><br>"
  15.  
  16. redirect_to import_new_contacts_path
  17. end
  18. end

联系型号

车型/ contact.rb

  1. def import import_file
  2. File.foreach( import_file.path ).with_index do |line,index|
  3.  
  4. # Process each line.
  5.  
  6. # For any errors just raise an error with a message like this:
  7. # raise "There is a duplicate in row #{index + 1}."
  8. # And your controller will redirect the user and show a flash message.
  9.  
  10. end
  11. end

希望有所帮助!

约书亚

猜你在找的Ruby相关文章