How to prevent carrierwave from adding the filename string to the mounted column when file is not uploaded?

I am using Rails and ActiveRecord. I have carrierwave mounted on one of the columns(:logo) of a model(Listing). My default filename is "disp_logo". Let's say I just do Listing.create! In this case, I haven't really uploaded any file. I did not do Listing.logo=<some file> or Listing.remote_logo_url=<some url>. But, carrierwave still inserts the string "disp_logo" in the :logo column. Why does it do that? How can I prevent carrierwave from doing so?

My uploader class has the following methods:

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

def filename
  "disp_logo"
end

That's what I mean by default filename. I want the column :logo to have NULL if image is not uploaded. Instead it has "disp_logo".

Answers


It would seem you created your migration with "disp_logo" as the default value for your column. You should set the default image in your uploader instead, like this:

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url
    "/" + [version_name, "disp_logo.jpg"].compact.join('_')
  end

Or if you use rails 3.1 and the assets pipeline:

  # Include the Sprokets helpers for Rails 3.1+ asset pipeline compatibility:
  include Sprockets::Helpers::RailsHelper
  include Sprockets::Helpers::IsolatedHelper

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url
    asset_path [version_name, "disp_logo.jpg"].compact.join('_')
  end

Edit:

Modify your filename method as follows:

  def filename
    "something.jpg" unless original_filename.nil?
  end

Need Your Help

Gotomeeting php api(oauth) implementation

php api oauth meeting

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:

I can't get images to show up in Eclipse

java eclipse image embedded-resource

I am fairly new to using Swing and I thought that in Eclipse all I would have to do is put an image file into the SRC directory and the program would have access to it. Of course this is not the c...