0
votes

Many users have asked same question but I am stacked..

Rails : 4.2.5

Carrierwave

Cloudinary

I want to upload an avatar image as default when a user is created.

class UsersController < ApplicationController
    after_action :set_default_avatar!, only: [:create]

    def create
       **************
       **************
    end

    def set_default_avatar!
       url = ImageUploader.default_url()
       @user.update_attribute(:avatar, url)
    end
end

class ImageUploader < CarrierWave::Uploader::Base

    def self.default_url()
        ActionController::Base.helpers.asset_path("fallback/" + "avatar_#{rand(1..15).to_s}.jpg"])
    end

end

once a user creation process is completed, then "after_action" is processed.

"default_url" returns a random image path which is located in 'public/fallbak/'.

I put the url in user.avatar, the users avatar has been updated as NULL. Neither no image was uploaded on Cloudinary.

Basically, I want to store images at Cloudinary service.

When a user edit users information at a screen, they could be able to upload avatar image.

However I cant upload an image as default avatar by the logic above.

I red the document of Carrierwave, but it doesn't work for me.

I believe that something is missing in my code.

Any help is very appreciated.

1
Are those fallback images pre-uploaded to Cloudinary? Why do you require it to re-upload every time a user is assigned with it? AFAIU the use-case you should utilize PreloadedFile class. See: cloudinary.com/documentation/rails_image_uploadNadav Ofir

1 Answers

1
votes

It's not uploading the file because ImageUploader.default_url is returning a relative path.

You have two options:

Add a host parameter to your asset_path:

# app/uploaders/image_uploader.rb
def self.default_url()
  ActionController::Base.helpers.asset_path("fallback/" + "avatar_#{rand(1..15).to_s}.jpg", host: 'http://example.com')
end

Or use File.open to attach the file from the filesystem:

def set_default_avatar!
  path = File.join(Rails.root, 'app/assets/images/fallbak', "avatar_#{rand(1..15).to_s}.jpg")
  File.open(path) do |f|
    @user.avatar = f
  end
end