0

I am using carrierwave to upload my image but failed. Please help me.

Versions used:

rails (4.0.1)
carrierwave (0.10.0)
carrierwave-mongoid (0.7.1)
carrierwave_backgrounder (0.4.1)

My uploader:

#<EventImageUploader:0x007fc6a948ede8 
@model=#<Event::EventImage 
_id: 5876f63b6c616cea34630000, 
c_at(created_at): 2017-01-12 03:21:31 UTC, 
image: nil, 
image_tmp: "1484191291-59956-9524/2016-12-10_23-45.jpg">,
@mounted_as=:image>

My image is nil, but the image under image_tmp exists. My sidekiq is running fine too.

Here is my worker:

class ImageWorker < ::CarrierWave::Workers::StoreAsset
  def perform(*args)
    super(*args)

    record = ::CarrierWave::Workers::Base.perform(*args)
    if record 
      p "success"
    else
      raise "record #{args} not found, failed"
    end

  end
end

How to make the upload works? Thank you.

Jeffrey C
  • 325
  • 3
  • 12

1 Answers1

0

After viewing the source of CarrierWave::Workers::StoreAsset#perform, the reason why the image cannot be uploaded is because of embedded documents.

The line from source record = resource.find id will return nil because resource is an embedded class and you cannot find id by an embedded class.

To solve the problem, see here. My code should work if I add the following:

class Event
  include Mongoid::Document

  embeds_many :images
end

class EventImage
  include Mongoid::Document

  embedded_in :Event

  mount_uploader :image, ImageUploader
  process_in_background :image

  def self.find(id)
    bson_id = Moped::BSON::ObjectId.from_string(id) # needed for Mongoid 3

    root = Event.where('images._id' => bson_id).first
    root.images.find(id)
  end
end

If you get the error uninitialized constant Moped::BSON, make sure to require it in the first place.

Jeffrey C
  • 325
  • 3
  • 12