0

I'm trying to upload a CSV file(without headers) to a form in Rails, and then change my database based on that file's contents.

Now, the problem I'm having is that I know my routes must be correct, because I'm able to get to the correct method...but, my @imported variable is saying it is nil even when I upload a file.

Is there any help I can get for this? This will be my first file upload in rails, so we can cross this milestone together...

Here is the form in my view, mapped to the #ship action:

<%= form_for @import, :url => {:action => "ship", :controller => "imports"} do |f| %>
    <%= f.file_field :import %>
    <%= f.submit %>
<% end %>

And here is the corresponding method in my controller:

def ship
   @import = CSV.read(params[:file])
   @import.each do |i|
      Product.ship(@import[i][0]) #I believe the #read method imports
   end                              #CSV files as an array of arrays
  redirect_to "/"                   #But I have yet to get past the 
 end                                #first line, so I'm unsure
5
  • possible that :import param is not permitted in your controller? Commented Sep 20, 2016 at 19:33
  • Would that just be as simple as adding params.permit.require(:import) to my controller? I didn't realize import needed that. Commented Sep 20, 2016 at 19:37
  • yes, and a way to check that is to see whether your logs return unpermitted parameter :import following the POST action. Commented Sep 20, 2016 at 19:39
  • Well, that changed my error to "no implicit conversion of hash to string". Which is odd, since I was certain CSV.read would turn it into an array of arrays rather than a hash. Commented Sep 20, 2016 at 19:45
  • 1
    @import vs @imported. Which is it? Also I think it should be params[:import][:import] Commented Sep 20, 2016 at 19:46

1 Answer 1

1

Sergio Tulentsev is right. You need to use params[:import][:import]. The first import being the name of your resource (comes from form_for @import, the second import being the field name (coming from f.file_field :import).

More info at http://guides.rubyonrails.org/form_helpers.html#uploading-files

Sign up to request clarification or add additional context in comments.

1 Comment

Well, that definitely got me where I needed to go. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.