问题
An Image model has a 1:1 association with an Organization model. In the organizations controller, the create
method calls on an Image model method called upload_file
.
def create
@organization = Organization.new(new_params)
if @organization.save
Image.upload_file(@organization.id)
end
end
The upload_file
method uses a carrierwave uploader to store a standard file in an Amazon S3 bucket. To this end, the Image model includes mount_uploader :file_name, ImageUploader
.
My question is how to create an Image instance for the uploaded file? The path to the stored file should be stored in the column file_name
in the Image model. And the organization associated with the image should be stored in the column organization_id
in the Image model. How can I do this? More specifically, what code should I add for this to the model method below? (also see the comments in the method below.
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
Currently in rails console
I get the following error:
>> 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.
回答1:
You don't have to call the uploader yourself. Carrierwave comes with a mechanism to do the uploading and storing in AR models for you:
class Organization < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
Then you can do
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'
Please visit the carrierwave README for more extensive examples.
来源:https://stackoverflow.com/questions/31594988/uploader-produces-errors-regarding-the-column-in-which-it-should-store-the-path