上传器产生有关应存储路径的列的错误

Image模型与Organization模型具有1:1的关联。 在组织控制器中, create方法调用名为upload_file的Image模型方法。

 def create @organization = Organization.new(new_params) if @organization.save Image.upload_file(@organization.id) end end 

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

我的问题是如何为上传的文件创建一个Image实例? 存储文件的路径应存储在Image模型的列file_name中。 与图像关联的组织应存储在Image模型的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 => # >> 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' 

有关更多示例,请访问carrierwave README 。