How to import file to Ruby on Rails system without receiving "No sunch file or directory @ rb_sysopen - file.txt

Asked

Viewed 102 times

0

My program reads a file . txt for example, iterates over the internal information and store in the database.

But at the time the file is sent he gives an error saying he does not know the file path... In my understanding, when the file was sent it was stored in the variable that is specified, but that’s okay.

The error is shown in the attached image. It is noticed that the pointed line is precisely where the file that is not found will be opened.

Controller

def import

  errors = []
  file = params['file']
  File.open(file).each do |line|
  begin
    line = line.split("\t")

    next if line[0] == "Comprador"

    buyer = line[0] rescue row[0]
    description = line[1] rescue line[1] 
    unity_price = line[2].to_f rescue line[2].to_f
    quantiti = line[3].to_i rescue line[3] .to_i
    address = line[4] rescue line[4] 
    provider = line[5] rescue line[5] 
    total_gross = "Total: #{(unity_price * quantiti).round(2)}"

    Record.create(buyer: buyer, description: description, unity_price: unity_price,  quantiti: quantiti,  address: address,  provider: provider)
  rescue Exception => err
    errors << err.message
  end
end

if errors.banck?
  flash[:success] = "Imported with successful"
else
  flash[:error] = errors.join(", ")
end
redirect_to "/file"

View

<%= form_tag import_path, method: :post do %>
 <div class="input-group no-border">
  <%= file_field_tag 'file' %>
  <%= button_tag 'submit'%>
 </div>
<% end %>

the program hangs on the line "File.open(file). each of |line|"

inserir a descrição da imagem aqui

1 answer

1


Your form must have the attribute enctype defined as multipart/form-data. Since you do not have this attribute, what you are receiving is only the file name, with this attribute you can do:

file_content = params['file'].read

This way you will have the contents of the file in file_content.

  • Show, I forgot about Multipart. About the read method, it was generating another error, as it transformed everything into a string and was passing the whole file as a name or something... After changing the . read to . path it passed the path!

  • Good! In the case of read, I meant instead of File.open(file) you can call params['file'].read.

  • Ah, yeah! Stay cool

Browser other questions tagged

You are not signed in. Login or sign up in order to post.