Attempting to utilize ActiveStorage for a simple image upload form. It creates successfully, but upon submission it throws an error:
undefined method `upload' for nil:NilClass Did you mean? load
This is the block it wants me to look at:
@comment = Comment.create! params.require(:comment).permit(:content)
@comment.image.attach(params[:comment][:image])
redirect_to comments_path
end
This is in the full controller:
class CommentsController < ApplicationController
def new
@comment = Comment.new
end
def create
@comment = Comment.create! params.require(:comment).permit(:content)
@comment.image.attach(params[:comment][:image])
redirect_to comments_path
end
def show
@comment = Comment.find(params[:id])
end
end
What should actually happen is it takes you to the page to view the upload. Here:
# new.html.erb
<%= form_with model: @comment, local: true do |form| %>
<%= form.text_area :content %><br><br>
<%= form.file_field :image %><br>
<%= form.submit %>
<% end %>
# show.html.erb
<%= image_tag @comment.image %>
Here's the comment.rb
class Comment < ApplicationRecord
has_one_attached :image
end
Error in the log:
app/controllers/comments_controller.rb:12:in `create'
Started POST "/comments" for 127.0.0.1 at 2018-07-15 21:30:23 -0400
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Al2SdLm1r6RWXQ6SrKNdUTWscSJ4/ha3h8C3xl6GvUsDhBGHkiesvGgyjL 5E1B1eyRUrYyjovFTQaGKwAZ1wtw==", "comment"=>{"content"=>"fdfdfdsdf", "image"=># <ActionDispatch::Http::UploadedFile:0xb3d36d8 @tempfile=#<Tempfile:C:/Users/tduke /AppData/Local/Temp/RackMultipart20180715-3328-10frg81.png>, @original_filename="9c6f46a506b9ddcb318f3f9ba34bcb27.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"comment[image]\"; filename=\"9c6f46a506b9ddcb318f3f9ba34bcb27.png \"\r\nContent-Type: image/png\r\n">}, "commit"=>"Create Comment"}
Completed 500 Internal Server Error in 468ms (ActiveRecord: 4.0ms)
NoMethodError (undefined method `upload' for nil:NilClass
Did you mean? load):
I solved it by making sure that my Active Storage configuration in my environment file was set.
So, in development.rb
, make sure the line
config.active_storage.service = :local
is present.
Try this:
@comment = Comment.new(params.require(:comment).permit(:content, :image))
@comment.save!
redirect_to comments_path
ActiveRecord is smart enough to know that image
is a file that is handled by ActiveStorage, so you don't need to manually attach it. I'm guessing that because the record is already persisted and the image isn't there it's throwing a fit.
Also you should move your strong params to a method.
def comment_params
params.require(:comment).permit(:content, :image)
end
And use like,
@comment = Comment.new(comment_params)
@comment.save!
redirect_to comments_path
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With