ruby-on-rails – 为什么活动存储会抛出这个错误:nil的未定义方法`upload’:NilClass,当object不是nil时

我在rails项目上设置了活动存储.我不断得到错误:

未定义的方法’upload’为nil:NilClass.

这就是我所做的.

>我已经运行了迁移:rails active_storage:install
>我编辑了我的开发环境文件:config.active_storage.service =:local
>与我的生产文件相同:config.active_storage.service =:amazon
>我确保使用has_one_attached:image正确设置了我的模型

我的控制器:

class EventsController < ApplicationController 
  def create
    @event = Event.new(event_params)
    @event.save
  end

  private

  def event_params 
    params.require(:event).permit(:name, :image)
  end
end

这是表格:

<%= simple_form_for(@event, url: events_path, method: :post) do |f| %>
  <%= f.input :name %>

  <%= f.input :image %>

  <%= f.submit %>
<% end %>

这是模型:

class Event < ActiveRecord::Base

  has_one_attached :image

  acts_as_list

end

值得一提的是,我正在将此特定项目升级到rails 5.它还习惯使用回形针.

问题:
当我提交此表单时,会抛出上述错误.相同
尝试更新@event对象时发生错误.

更新

>在查看框架跟踪时,错误将在此行上抛出:blob.upload io.奇怪的是,当我调试这条线时,blob不是零.它拥有一个没有id的ActiveStorage :: Blob.而且io也不是零.

错误日志:

我故意取出真品令牌.

Started POST "/events" for ::1 at 2018-08-23 10:02:25 -0600
Processing by EventsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"*****************", "event"=>{"name"=>"test event", "image"=>#<ActionDispatch::Http::UploadedFile:0x00007fc816e90af8 @tempfile=#<Tempfile:/var/folders/f9/q3x5477d1dxd7fxjbrl2tvch0000gn/T/RackMultipart20180823-61111-14dih2d.jpg>, @original_filename="sample-image.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"event[image]\"; filename=\"sample-image.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Update Event"}
Completed 500 Internal Server Error in 61ms (ActiveRecord: 0.0ms)



NoMethodError (undefined method `upload' for nil:NilClass):

app/controllers/events_controller.rb:4:in `create'
::1 - - [23/Aug/2018:10:02:25 MDT] "POST /events HTTP/1.1" 500 138644
http://localhost:3000/ -> /events

最佳答案 您应该将这行代码添加到您的Gemfile:

gem 'aws-sdk-s3', require: false

然后将此另外添加到您的环境/生产中:

config.active_storage.service = :amazon # or wharever storage you are using...
点赞