Reputation: 5702
A model is seeded with a remote url for an image, meaning the db entry it is not created in Rails. Then the first time it is fetched from the DB in Rails I want to detect that the image has not been uploaded, assign the remote_seed_url for the image url and save! to trigger the CarrierWave upload. I want to do this only once, obviously, but the code below sometimes uploads the same image more than once.
class Item
include Mongoid::Document
include Sunspot::Mongoid2
field :image, type: String
field :remote_seed_url, type: String #URL for image
mount_uploader :image, ImageUploader
end
Then in a controller
def show
@ item = Item.find(params[:id])
# if CarrierWave has already uploded then do nothing
if [email protected]?
@item.image = @item.remote_seed_url # next save will trigger the upload?
@item.save!
end
respond_to do ...
end
The value of @item.image is usually "new" or "old" and @item.image? sometimes returns false when I can see that it has already uploaded the image. This causes the above code to upload multiple times.
Upvotes: 4
Views: 3208
Reputation: 2054
After uploader is mounted on a field, when you call that field, you get an uploader object. If you want to check if there is a file, you should call "file" on that object:
[1] pry(main)> item.image.class
=> ImageUploader
[2] pry(main)> item.image.file.class
=> CarrierWave::SanitizedFile
[3] pry(main)> item.image.file.nil?
=> false
Upvotes: 3