Rails] Images erased after a new commit on heroku

2019-04-02 04:01发布

问题:

I'm using Carrierwave to upload images, and my app is on Heroku right now. Images are uploaded successfully unless I push a new commit to heroku. Images that I uploaded before a push seem to be erased when a new commit comes in. Does anyone know the reason behind and how to fix this issue?

Update: The problem becomes, using carrierwave on Heroku without a storage server like Amazon EC3. Heroku does not save files in public folder, where carrierwave uploads by default.

app/uploaders/image_uploader.rb:

  def store_dir
   "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

And you need to change this to somewhere in the tmp folder in order to preserve your image files after each commit. I tried to change it to

"#{Rails.root}/tmp/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"

But it does not work. I checked on my local environment, and the image is stored in the right location successfully. So I guess if I just set the routes to the right location, this could work. Could someone help me with this?

回答1:

Since Heroku does not allow storing static files (unless it's associated the application itself), you should make Carrierwave upload to a remote repository (e.g. Amazon S3) using fog. Everytime a user uploads a file, the file will be automatically uploaded to your S3 storage instead of Heroku.