Delving into Rails’ upload functionality and actually following this railsguide.
I use the following code for the upload form:
<%= form_tag({ action: :upload }, multipart: true) do %>
<%= file_field_tag :picture %>
<%= submit_tag %>
<% end %>
And this is my upload method:
def upload
uploaded_io = params[:customer][:picture] #erroneous line!!
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
file.write(uploaded_io.read)
end
flash[:notice] = "File uploaded successfully!"
redirect_to root_path
end
I have marked the line which I believe is erroneous in the second code snippet. The upload method is just pasted from the railsguide and I adjusted the params array to [:customer].
When uploading a file I get this error:
undefined method `[]' for nil:NilClass
It refers to the line I marked above.
I also found this other question, but I haven’t figured out yet how that might help me.
What am I doing wrong? Is my form wrong or my controller method? Any help appreciated.
Try changing to
Can always look at the logs to see how the request parameters hash is structured. When you use a form_for in rails, let’s say on a customer object like below. You then get the fields as
But since you just used the form_tag helper, it’s not encased in another hash: