【发布时间】:2018-12-23 11:52:53
【问题描述】:
尝试将 ActiveStorage 用于简单的图像上传表单。它创建成功,但提交时抛出错误:
undefined method `upload' for nil:NilClass Did you mean? load
这是它要我看的块:
@comment = Comment.create! params.require(:comment).permit(:content)
@comment.image.attach(params[:comment][:image])
redirect_to comments_path
end
这是在完整的控制器中:
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
实际上应该发生的是它会将您带到页面以查看上传。这里:
# 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 %>
这是comment.rb
class Comment < ApplicationRecord
has_one_attached :image
end
日志中的错误:
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
你的意思是?加载):
【问题讨论】:
-
您在 `Comment.create!1 中有任何错误吗?将您的许可方法移动到私有方法是标准做法。
-
这发生在哪一行?
-
@JoshBrody Line 9
-
在您的项目中对
upload进行全文搜索,并告诉我们它在哪里发生以及它在做什么——Image模型中是否有一个upload方法作为一个运行after_save还是什么?您需要提供更多详细信息,我们才能解决您的问题 -
显示
Comment和Image模型类的全部内容
标签: ruby-on-rails ruby