Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks carrierwaveuploader/carrierwave · GitHub carrierwave - classier solution for file uploads for rails, sinatra and other ruby web frameworks

Displaying a Carrierwave filename in the view

I am trying to display the filename of a Carrierwave attachment in a Rails erb template. The following does not work:

<%= @page.form.filename %>

This seems in line with the documentation. Is some additional step needed?

My page model looks like this:

class Page < ActiveRecord::Base

  mount_uploader :form, FormUploader


The form uploader looks like this:

class FormUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir

  def extension_white_list


Source: (StackOverflow)

Reprocessing images in Carrierwave

Let's say my model has an image with :thumb and the client wants :tiny and :nano thumbnails.

How do I reprocess all the existing images using a rake task?

I've found a rask that I thought would do it but it's giving me errors.

Source: (StackOverflow)

Undefined method `image_will_change!' for CarrierWave on Heroku

I have a simple model that mounts a Carrierwave uploader. Everything works fine in development, but I get an undefined method "image_will_change!" error on heroku.

class Receipt < ActiveRecord::Base
  mount_uploader :image, ImageUploader

class ImageUploader < CarrierWave::Uploader::Base
  storage :fog
  def store_dir

I have the cache_dir set appropriately as well according to the Carrierwave Wiki.

receipt.image = "public/images/test.jpg" #works fine in development, fails in heroku

Source: (StackOverflow)

Carrierwave - Resizing images to fixed width

I'm using RMagick and want my images to be resized to a fixed width of 100px, and scale the height proportionally. For example, if a user were to upload a 300x900px, I would like it to be scaled to 100x300px.

Source: (StackOverflow)

validate size of upload using Carrierwave

In our latest application we need to process some uploads, I've worked with paperclip before and everything just works! but we're giving carrierwave a try, it looks promising but, I can't find how to validate the size of an attachment, it seems like the documentation doesn't have any information about it, should we add it manually to the model via a custom validator?

Thanks in advance!

Source: (StackOverflow)

CarrierWave: Create the same, unique filename for all versioned files

Before I go into detail I'll get right to the point: has anyone figured out a way to get Carrierwave to save files with their names as a timestamp or any arbitrary string that is unique to each file?

By default Carrierwave saves each file and its alternate versions in its own directory (named after the model ID number). I'm not a fan of this because instead of one directory with 1,000, for the sake of using a large round number, files (in my case pictures) in it we get one directory with 1,000 subdirectories each with one or two files. Yuck.

Now, when you override your Uploader's store_dir method to be something like the following:

def store_dir

you end up with the exact behavior that I want. All the files (pictures) go into one big happy folder. No more subfolders that stick around when the object gets deleted.

There's only one problem. File collisions. If you upload delicious_cake.jpg twice the second one will overwrite the first even if they are two different pictures of delicious cake! That's clearly why the store_dir method has the extra /#{} tacked on the end of the value it returns.

So, what to do? After reading around a bit I discovered that in the generated uploader file there is an apparent solution commented out.

# Override the filename of the uploaded files:
# Avoid using or version_name here, see uploader/store.rb for details.
# def filename
#   "something.jpg" if original_filename
# end

After a little bit of searching I found someone who had done the following

def filename
  @name ||= "#{secure_token}.#{file.extension}" if original_filename

This got me thinking, why not just do this

def filename
  @name ||= "#{( +, '0')}#{File.extname(original_filename)}"

That's when things got horribly broken. The problem with this is that filename apparently gets called for each version of the file so we end up with file names like 1312335603175322.jpg and thumb_1312335603195323.jpg. Notice the slight difference? Each file name is based on the time when filename was called for that particular version. That won't do at all.

I next tired using model.created_at for the basis of the timestamp. Only one problem, that returns nil for the first version since it hasn't been put in the database yet.

After some further thinking I decided to try the following in my pictures controller.

def create
  if params[:picture] and params[:picture][:image]
    params[:picture][:image].original_filename = "#{( +, '0')}#{File.extname(params[:picture][:image].original_filename)}"

This overrides the original_filename property before Carrierwave even gets to it making it be a timestamp. It does exactly what I want. The original version of the file ends up with a name like 1312332906940106.jpg and the thumbnail version (or any other version) ends up with a name like thumb_1312332906940106.jpg.

But, this seems like an awful hack. This should be part of the model, or better yet part of the uploader mounted onto the model.

So, my question is, is there a better way to achieve this? Did I miss something crucial with Carrierwave that makes this easy? Is there a not so obvious but cleaner way of going about this? Working code is good, but working code that doesn't smell bad is better.

Source: (StackOverflow)

Downloading and zipping files that were uploaded to S3 with CarrierWave

I have a small Rails 3.2.1 app that uses CarrierWave 0.5.8 for file uploads to S3 (using Fog)

I want users to be able to select some images that they'd like to download, then zip them up and send them a zip. Here is what I've come up with:

def generate_zip
  #A collection of Photo objects. The Photo object has a PhotoUploader mounted.
  photos = Photo.all

  tmp_filename = "#{Rails.root}/tmp/" <<'%Y-%m-%d-%H%M%S-%N').to_s << ".zip"
  zip =, Zip::ZipFile::CREATE)

  photos.each do |photo|
    file_to_add =
    zip =
    zip.add("tmp/", file_to_add.path)

  #do the rest.. like send zip or upload file and e-mail link


This doesn't work because returns an instance of CarrierWave::Storage::Fog::File instead of a regular file.

EDIT: The error this leads to:

Errno::ENOENT: No such file or directory - uploads/photos/name.jpg

I also tried the following:

tmp_filename = "#{Rails.root}/tmp/" <<'%Y-%m-%d-%H%M%S-%N').to_s << ".zip"
    zip =, Zip::ZipFile::CREATE)

    photos.each do |photo|
      processed_uri = URI.parse(URI.escape(URI.unescape("[", "%5B").gsub("]", "%5D"))
      file_to_add =
      zip =
      zip.add("tmp/", file_to_add.path)

But this gives me a 403. Some help would be greatly appreciated.. It probably is not that hard I'm just Doing it Wrong™

Source: (StackOverflow)

Rails: carrierwave uninitialized constant error

I have Rails 3

Carrierwave 0.5.4


class FastaUploader < CarrierWave::Uploader::Base
  storage :file
  def store_dir


class AddFileUpToCvits < ActiveRecord::Migration
  def self.up
    add_column :cvits, :fasta, :string

  def self.down
    remove_column :cvits, :fasta


class Cvit < ActiveRecord::Base
    attr_accessible :fasta
    mount_uploader :fasta, FastaUploader


<%= form_for(@cvit, :html => {:multipart => true, :onsubmit => "return ray.ajax()" }) do |f| %>
  <%= f.file_field :fasta %><br></br>
  <div class="actions">
    <%= f.submit "Submit"%>
<% end %>

I get this error: uninitialized constant Cvit::FastaUploader

Any suggestions???

Source: (StackOverflow)

rspec testing carrierwave - newbie

I'm making a rails 3.1 app using carrierwave to upload files to aws s3. I've followed the instructions on the carrierwave github repository and am now able to upload files to my aws bucket. It's the testing that got me stuck. Over the last two days I've been googling and revising, using all the other Q&A's I've found but am finally crying 'mama.' Here's what I've got:


storage :fog

def store_dir


if Rails.env.test? or Rails.env.cucumber?
  CarrierWave.configure do |config| = :file
    config.enable_processing = false


require 'spec_helper'
require 'support/fog_helper'
require 'carrierwave/test/matchers'

describe ImageFileUploader do
  include CarrierWave::Test::Matchers

  before do
    ImageFileUploader.enable_processing = true
    @user = Factory(:user, :email => "")
    @uploader =, Factory(:image))!("#{Rails.root}/tmp/uploads/#{Rails.env}/images/"))

  after do
    ImageFileUploader.enable_processing = false

  context 'the tiny version' do
    it "should scale down a landscape image to be exactly 50 by 50 pixels" do
      @uploader.tiny.should have_dimensions(50, 50)


Factory.define :image do |image|
  include ActionDispatch::TestProcess

  image.date_taken            "Sun, 09 Oct 2011"
  image.time_taken            "2000-01-01 03:41:00 UTC"
  image.image_file            fixture_file_upload('spec/support/test_images/audi.png', 'image/png')
  image.taken_by              "John Doe"
  image.collection            "N/A"
  image.comments              "Beautiful day!"
  image.association   :user


While my /public/uploads/tmp/ is getting filled up with 'tiny' (and other versions) of the images whose generation I am testing, the tests continue to fail with the following error message:

1) ImageFileUploader the tiny version should scale down a landscape image to be exactly 50 by 50 pixels

 Failure/Error: @uploader =, Factory(:image))
   Expected(200) <=> Actual(404 Not Found)
     request => {:expects=>200}
     response => #<Excon::Response:0x0000010569f928 @body="", @headers={}, @status=404>
 # ./spec/uploaders/image_file_uploader_spec.rb:11:in `block (2 levels) in <top (required)>'

I know that the above means that rspec isn't finding my testing bucket. Anyone have any thoughts about what I'm doing wrong?

would be super grateful for any new leads.

UPDATE: 10/11/11 The file upload works but I've stalled in figuring out how to get test involving the images to pass. In the short term, I will use a placeholder image as I flesh out the rest of my app and return to this later. I'll post a further update once I figure this out. (Do leave any thoughts if you have any insights, however.)

Source: (StackOverflow)

Carrierwave; multiple uploaders or just one?

I have a post model and a podcast model. Both models have an attribute titled: image. I'm using one Carrierwave uploader (named ImageUploader) to handle both models. I have two questions before I go into production.

Dumb question:

Is it ok to use the same uploader for two different models when they both have the same attribute name for their file attachements? sorry if it seems obvious

Main question:

I want to create three versions of each blog post image (thumb, large, sepia) and only 1 version of each podcast image (thumb).

Do I need to use two uploaders now or can I namespace with the one that I'm already using?

Again it probably seems obvious. I could probably have written the second uploader in the time its taken me to ask these questions

Source: (StackOverflow)

Factory with carrierwave upload field [duplicate]

This question already has an answer here:

Hello i need to build up Factory for my model, for example

Factory.define :farm do |f| { :name }
  f.harvest '3'
  f.offers 'Random'
  f.latitude '43'
  f.longitude '-70'
  f.about 'We rocks!'
  f.logo { :logo } # this doesn't work

For now im just pass string "#{n}.jpg" into my logo field and this dont work, how to evalute this field? Im using CarrierWave for uploading.

Source: (StackOverflow)

Uploading a remote file url from Rails Console with Carrierwave

I just wanted to know how one would go about uploading a remote file url using Carrierwave in the Rails console.

I tried the following without any luck. I presume it's not processing the Uploader?

user = User.first
user.remote_avatar_url = ""

Many thanks

Source: (StackOverflow)

Deleting files in ruby

I'm using the carrierwave gem to upload files. I have built a system for users to flag images as inappropriate and for admins to remove the images. From what I can tell, calling destroy on the image will only remove the path name from the tabel. Is there a way to have ruby actually remove the file itself? Or should rails be automatically removing the file when I destroy the image path?

Source: (StackOverflow)

Carrierwave files with Capistrano

I'm using rails 3.2 with asset and carrierwave for upload some images, they store in /public/uploads/photo/..... but when I do a cap:deploy (with capistrano) my current directory application doesn't contain the files I uploaded, because capistrano make a new version ....

=== Update ===

After all I use this :

inside :deploy namespace

   task :symlink_uploads do
     run "ln -nfs #{shared_path}/uploads  #{release_path}/public/uploads"

and after:

after 'deploy:update_code', 'deploy:symlink_uploads'

=== Re Update ===

The solution of @tristanm is the best way to solve this.

Source: (StackOverflow)

Seeding file uploads with CarrierWave, Rails 3

I'm trying to seed a database in Rails 3 with images using CarrierWave, however nothing I try seems to work short of having to upload them all by hand.

pi = => product)
pi.image =, 'test.jpg'))
pi.store_image! # tried with and without this
product.product_images << pi!

Anybody know how to seed using CarrierWave at all?

Source: (StackOverflow)