CarrierWave: Detects that the image is already loaded.

The model is seeded with a remote URL for the image, which means that the db entry is not created in Rails. Then the first time it is retrieved from the database in Rails, I want to detect that the image has not been uploaded, assign remote_seed_url to the image URL and save! to start the CarrierWave download. I want to do this only once, obviously, but the code below sometimes loads 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 the controller

def show
    @ item = Item.find(params[:id])
    # if CarrierWave has already uploded then do nothing
    if !@item.image?
        @item.image = @item.remote_seed_url # next save will trigger the upload?
        @item.save!
    end
    respond_to do ...
end

Is the value of @ item.image usually "new" or "old" and @ item.image? sometimes returns false when I see that it has already uploaded the image. This causes the above code to load several times.

  • Is the controller code correct to download the image only once?
  • - , @item.image? false, ? , ?
+4
1

, , , uploader. , , "" :

[1] pry(main)> item.image.class
=> ImageUploader
[2] pry(main)> item.image.file.class
=> CarrierWave::SanitizedFile
[3] pry(main)> item.image.file.nil?
=> false
+3

All Articles