Last Updated: February 25, 2016
· brain64bit

Using Carrierwave uploader for tableless model in Rails

Repost from my blog, 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

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

And you can test from rails console :

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

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}

Ref :

2 Responses
Add your response


Thanks for this. Just what I needed! :)

over 1 year ago ·

Thanks, simple and clear solution.

over 1 year ago ·