How to upload a text file and analyze the contents in a database in RoR

So far I have managed to upload the file:

# In new.html.erb <%= file_field_tag 'upload[file]' %> 

And access the file in the controller

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

However, this only gives me the file name, not the contents of the file. How to access its contents?

I know this is a jump, but as soon as I can access the contents of the file, can everything load the folder and iterate through the files?

+6
source share
2 answers

Full example

Take, for example, loading an import file containing contacts. You do not need to store this import file, just process it and discard it.

Routes

routes.rb

 resources :contacts do collection do get 'import/new', to: :new_import # import_new_contacts_path post :import # import_contacts_path end end 

The form

view / contacts / new_import.html.erb

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

controller

Controllers / contacts _controller.rb

 def new_import end def import begin Contact.import( params[:contacts][:import_file] ) flash[:success] = "<strong>Contacts Imported!</strong>" redirect_to contacts_path rescue => exception flash[:error] = "There was a problem importing that contacts file.<br> <strong>#{exception.message}</strong><br>" redirect_to import_new_contacts_path end end 

Contact Model

/contact.rb models

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

Hope this helps!

Joshua

+7
source

In new.html.erb

 <%= form_tag '/controller/method_name', :multipart => true do %> <label for="file">Upload text File</label> <%= file_field_tag "file" %> <%= submit_tag %> <% end %> 

In the controller # method_name

 uploaded_file = params[:file] file_content = uploaded_file.read puts file_content 

see more for uploading a file to rails http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm How to read an entire file in Ruby?

Hope this helps you.

+5
source

Source: https://habr.com/ru/post/914780/


All Articles