read

In this post i want to share my experience in implementing Carrierwave for tableless model, for example i’ve model User :

class User
attr_accessor :id, :name, :avatar
...
end

I need to store user’s avatar using carrierwave, in this case i create AvatarUploader, the problem is how i store avatar from instantiating User model ? If your class is subclass of ActiveRecord::Base, you can use mount_uploader method, but if you have model like User which is not subclass of ActiveRecord::Base you will get exception :

undefined method `mount_uploader' for User:Class

Based on carrierwave documentation you can use mount_uploader if your class extend CarrierWave::Mount module and your class will have capability to store a file using instance method store_(mounted_field)! or cache_(mounted_field)!. So lets refactor our User model :

class User
extend CarrierWave::Mount
attr_accessor :id, :name, :avatar
mount_uploader :avatar, AvatarUploader
...
def save
self.store_avatar!
end
...
end

And you can test from rails console :

u = User.new(id:1, name:“swagger”) u.avatar = File.open(some_avatar_image_file_path) u.save

from rails console, a some version of avatar will created in public/tmp/timestamp/ when you assign image file to avatar field, when method save executed it will be move to public/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}

Blog Logo

Agung Prasetyo


Published

Image

devblog of @sgt_mactavish

Back to Overview