上传器产生关于它应该存储路径的列的错误

Uploader produces errors regarding the column in which it should store the path

图像模型与组织模型有 1:1 关联。在组织控制器中,create 方法调用名为 upload_file.

的图像模型方法
def create
  @organization = Organization.new(new_params)
  if @organization.save
    Image.upload_file(@organization.id)
  end
end

upload_file 方法使用载波上传器将标准文件存储在 Amazon S3 存储桶中。为此,Image模型包括mount_uploader :file_name, ImageUploader.

我的问题是如何为上传的文件创建Image实例?存储文件的路径应存储在 Image 模型的 file_name 列中。与图像相关联的组织应存储在图像模型中的列 organization_id 中。我怎样才能做到这一点?更具体地说,我应该为此将什么代码添加到下面的模型方法中? (另请参阅下面方法中的注释。

def self.upload_file(organization_id)
  file = 'app/assets/emptyfile.xml'
  uploader = ImageUploader.new
  uploader.store!(file)
  # Am I correct to assume that the previous line uploads the file using the uploader, but does not yet create an Image record?
  # If so, then perhaps the next line should be as follows?:
  # Image.create!(organization_id: organization_id, filename: file.public_url)
  # I made up "file.public_url". What would be the correct code to include the path that the uploader stored the image at (in my case an Amazon S3 bucket)?
end

目前在 rails console 我收到以下错误:

>> uploader = ImageUploader.new
=> #<ImageUploader:0x00000005d24f88 @model=nil, @mounted_as=nil, @fog_directory=nil>
>> file = 'app/assets/emptyfile.xml'
=> "app/assets/emptyfile.xml"
>> uploader.store!(file)
CarrierWave::FormNotMultipart: CarrierWave::FormNotMultipart
  from /usr/local/rvm/gems/ruby-2.2.1/gems/carrierwave-0.10.0/lib/carrierwave/uploader/cache.rb:120:in `cache!'
  etc.

您不必自己调用上传器。 Carrierwave 自带一种机制,可以为您上传和存储 AR 模型:

class Organization < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

那你可以

u = Organization.new
u.image = params[:file] # Assign a file like this, or

# like this
File.open('somewhere') do |f|
  u.image = f
end

u.save!
u.image.url # => '/url/to/file.png'

u.image.current_path # => 'path/to/file.png'
u.image # => 'file.png'

请访问载波 README 以获取更多示例。