Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave: set image path and skip the upload

I would like to set some images without uploading. (They already exist, or another task saves them...)

If I try (in rails console):

user = User.last
user.picture = '/some/picture.jpg'
user.save
user.picture # nil

The only way to do that is to set remote_picture_url, and then delete the upload (which is stupid)

Is there any method in carrierwave that lets you modify only the filename ?

like image 639
Benjamin Crouzier Avatar asked Jul 17 '13 15:07

Benjamin Crouzier


1 Answers

class User < ActiveRecord::Base
  attr_accessible :picture
  # Don't want to write to the database, but want to be able to check
  attr_writer :skip

  # set a default value
  def skip
   @skip ||= false
  end

  mount_uploader :image, PictureUploader

  # Make sure that the skip callback comes after the mount_uploader
  skip_callback :save, :before, :store_picture!, if: :skip_saving?

  # Other callbacks which might be triggered depending on the usecase
  #skip_callback :save, :before, :write_picture_identifier, id: :skip_saving?

  def skip_saving?
    skip
  end
end

class PictureUploader < Carrierwave::Uploader::Base
  # You could also implement filename=
  def set_filename(name)
    @filename = name
  end
end

Assuming you have the setup above, in your console:

user = User.last
user.picture.set_filename('/some/picture.jpg')
user.skip = true
# Save will now skip the callback store_picture!
user.save
user.picture # /some/picture.jpg

It should be noted that if you're in the console and you update an existing record that has an attached file (ie user.picture.file) it will show the old url/location. If you quit the console (assuming you're not in sandbox mode) and come back and query the same object it will have the updated url/location.

like image 176
Christopher Nguyen Avatar answered Sep 30 '22 06:09

Christopher Nguyen