4

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 !@item.image?
        @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.

  1. Is the controller code correct to get the image uploaded only once?
  2. Is there some way I might have messed things up and caused @item.image? to return false when it should be true? Maybe image aging?
pferrel
  • 5,673
  • 5
  • 30
  • 41
  • To further complicate this I run a job that layers new data into the objects periodically, which may change the timestamps. Could this be a problem with CarrierWave? the Layering does not alter the field CarrierWave is mounted on. – pferrel Nov 07 '13 at 20:15
  • No one seems to know CarrierWave? Oh, well I've added my own flag in the DB that is set on first upload. I check it before triggering another one. This solves the problem but in a non-CarrierWave way. – pferrel Nov 11 '13 at 17:23

1 Answers1

3

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
bosskovic
  • 2,034
  • 1
  • 14
  • 29