T. *_*uke 9 ruby ruby-on-rails
尝试将ActiveStorage用于简单的图像上载表单.它成功创建,但在提交时会抛出错误:
undefined method `upload' for nil:NilClass Did you mean? load
Run Code Online (Sandbox Code Playgroud)
这是它要我看的块:
@comment = Comment.create! params.require(:comment).permit(:content)
@comment.image.attach(params[:comment][:image])
redirect_to comments_path
end
Run Code Online (Sandbox Code Playgroud)
这是完整的控制器:
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
Run Code Online (Sandbox Code Playgroud)
实际应该发生的是它会带你到页面查看上传.这里:
# 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 %>
Run Code Online (Sandbox Code Playgroud)
这是comment.rb
class Comment < ApplicationRecord
has_one_attached :image
end
Run Code Online (Sandbox Code Playgroud)
日志错误:
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
Run Code Online (Sandbox Code Playgroud)
你的意思是?加载):
Uel*_*elb 32
如果有人有同样的问题,我只是通过确保我的环境文件中的活动存储配置已设置来解决它.
所以development.rb,确保线条
config.active_storage.service = :local
存在.
尝试这个:
@comment = Comment.new(params.require(:comment).permit(:content, :image))
@comment.save!
redirect_to comments_path
Run Code Online (Sandbox Code Playgroud)
ActiveRecord 足够聪明,可以知道这image是一个由 ActiveStorage 处理的文件,因此您无需手动附加它。我猜想,因为记录已经保留,而图像不存在,所以它会大发雷霆。
另外,您应该将强参数移至方法中。
def comment_params
params.require(:comment).permit(:content, :image)
end
Run Code Online (Sandbox Code Playgroud)
并使用像,
@comment = Comment.new(comment_params)
@comment.save!
redirect_to comments_path
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2541 次 |
| 最近记录: |