Adanos
Adanos

Reputation: 111

Carrierwave: Mount Uploader in non ActiveRecord inherited class

So, I have a shopping cart class I keep saved in session until the purchase is completed and I need to be able to upload a file into the cart (don't ask why, long story) once the purchase is finished, I dump all that information into a class that is saved in the DB.

I've used Carrierwave quite a lot and I didn't have any issues so far, but when I tried to mount an uploader into it I got

undefined method `mount_uploader' for Cart:Class

The question is, is it possible to mount an uploader into a class that doesn't inherit ActiveRecord:Base or am I having another issue altogether? I haven't been able to make it work so I don't want to waste more time if that's the issue.

Upvotes: 3

Views: 1525

Answers (1)

user1870776
user1870776

Reputation: 186

If you have model that isn't a subclass of ActiveRecord::Base you will get that exception:

undefined method `mount_uploader' for Derp:Class

Happily, you can use mount_uploader if your class extends the CarrierWave::Mount module AND that class has a save method that calls the instance method store_(mounted_field)!

In summary, the ActiveRecord::Base-less class will look something like

class Derp
    extend CarrierWave::Mount
    attr_accessor :name, :image
    mount_uploader :image, ImageUploader

    def save
        self.store_image!
    end
end

Upvotes: 5

Related Questions