Question

I have a problem with default_url method in Carrierwave as it doesn't work. My code looks like this

      class ImageFileUploader < CarrierWave::Uploader::Base

      include CarrierWave::MiniMagick

      storage :file
      def store_dir
          "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
      end
      version :small do
        process :resize_to_fill => [75, 75]
      end
      version :thumb do
        process :resize_to_fill => [120, 120]
      end
      version :medium do
        process :resize_to_fill => [639, 426]
      end
      def extension_white_list
        %w(jpg jpeg gif png)
      end
      version :thumb_default_avatar do
         process :resize_to_fill => [120, 120]
      end
      def default_url
        ActionController::Base.helpers.asset_path("fallback/" + [thumb_default_avatar.jpg,  
        "default_avatar.jpg"].compact.join('_'))
      end
      end

and I have this model which I need to set its avatar with the default_avatar image

    class Agent < ActiveRecord::Base
      mount_uploader :avatar, ImageFileUploader 
    end

Also I created a "fallback" folder included the default_avatar.jpg image in the "public" folder.

Thanks in advance.

Était-ce utile?

La solution 2

It works fine with me, when I changed the default_url method as shown

    def default_url
      /fallback/default_avatar.jpg'
    end

Thanks @Kirti Thorat, I understood your explanation about saving in DB.

Autres conseils

For default_url method to work, you would have to place the version specific default images i.e., small_default_avatar.jpg, thumb_default_avatar.jpg and medium_default_avatar.jpg in public/fallback(Note within public) folder. So, when you don't upload an image for a record then the CarrierWave would display the image from default_url instead of showing the broken image icon.

UPDATE

As per the code shared for ImageFileUploader, you are creating 4 versions of whatever image you upload namely :small, :thumb, :medium and :thumb_default_avatar. That's why, logically you should place version specific default images in the public/fallback folder. So, for example in your Agent show view if you are trying to render image with version :small and image was not uploaded while Agent creation then instead of showing broken image the default image for version :small i.e., small_default_avatar.jpg would be picked up to be displayed.

UPDATE 2

Default urls are not saved in the database. At runtime, CarrierWave checks whether or not an image was uploaded for an Agent. If image was uploaded it displays the image from stored directory and if image was not uploaded it directly displays the default image. So, no you are not supposed to store default url's in the database.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top