首页 > 解决方案 > nil:NilClass 的未定义方法 `upload' 你的意思是?加载

问题描述

尝试将 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

你的意思?加载):

标签: ruby-on-railsruby

解决方案


我通过确保在我的环境文件中设置了我的 Active Storage 配置来解决它。

所以,在 中development.rb,确保行

config.active_storage.service = :local

存在。


推荐阅读