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

Replacing aborts() for unresolved errors in iPhone/CoreData

iphone core-data abort

I have quite a few places in my iPhone application with a line like this:

Add a record to an existing user

ruby-on-rails-4 devise

The goal is to add a record to a table called Result. If the user(email) does not exist the user Table it will create a new account and after that create the Result record.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.