4

I have two models, each with their own Carrierwave uploaders:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end

and:

class Bookshelf < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

I want the user's avatar to be the latest bookshelf image he's uploaded. I try to achieve this like so:

class BookcasesController < ApplicationController
  def create
    @bookcase = current_user.bookcases.build(params[:bookcase])
    if @bookcase.save
      current_user.avatar = @bookcase.image
      current_user.avatar.recreate_versions!
    end
  end
end

Unfortunately, this has no effect on the avatar at all. How else might I achieve this?

nullnullnull
  • 8,039
  • 12
  • 55
  • 107

2 Answers2

9
current_user.avatar = @bookcase.image
current_user.avatar.recreate_versions!

Doesn't actually save --- you can either:

current_user.avatar.save

or as you put:

current_user.update_attribute(:avatar, @bookcase.image)
David Routen
  • 349
  • 4
  • 21
Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
  • Hi @JesseWolgamott, this work perfectly when you try to copy an image the first time, if you try to copy it again for the second time, it won't create the folder with the expected second copied image, do you know why ? – medBouzid Jan 02 '14 at 15:01
  • @medBo -- no, not without code. You should open a question referencing this one. – Jesse Wolgamott Jan 02 '14 at 19:08
  • i have already posted this question here : http://stackoverflow.com/questions/20869646/why-carrierwave-image-is-not-duplicated-the-second-time – medBouzid Jan 02 '14 at 19:14
  • 2
    When copying remote files (eg. S3) between models, check out `remote_*_url`: http://stackoverflow.com/questions/20361702/carrierwave-creating-a-duplicate-attachment-when-duplicating-its-containing-mod – Jared Beck Apr 16 '14 at 20:46
  • @JesseWolgamott `current_user.avatar.save` doesn't work, uploader doesn't have a `save` method – RocketR Nov 26 '14 at 10:40
  • Thank you! `current_user.update_attribute(:avatar, @bookcase.image)` works for me as well as `current_user.avatar = @bookcase.image` – Salma Gomaa Oct 28 '19 at 15:03
1

If your image file is stored locally and you don't mind opening a file descriptor, you could also do this:

current_user.avatar = File.open(@bookcase.image.path)
current_user.save
dhulihan
  • 11,053
  • 9
  • 40
  • 45