Carrierwave`default_url`没有触发

时间:2017-08-22 15:49:24

标签: ruby-on-rails carrierwave

我正在尝试让carrierwave为没有上传任何图像的记录显示默认图像。

我正在使用carrierwave默认代码。在app / uploaders / image_uploader.rb下:

def default_url
  ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
end

我将我的默认图片“default.png”存储在assets / images / fallback中。

在我的观点中,我正在使用图片助手标记:     <%= image_tag @ listing.images.first.url%> 注意:@listing是记录的实例

对于有图像的记录,显示没有问题。对于没有图像的记录,我得到一个错误“未定义的方法`url'代表nil:NilClass”。

在观看中的byebug:

  • 对于包含图像的记录:@record.images返回一个数组 其中的图像文件名。
  • 对于没有图像的记录:@record.images返回一个空数组。

当byebug放在default_url内时,当没有图像的记录被访问时,它根本不被触发。

[完整代码]
应用程序/上传/ image_uploader.rb:

class ImageUploader < CarrierWave::Uploader::Base

# Include RMagick or MiniMagick support:
  include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  # storage :file
  storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url(*args)
    # For Rails 3.1+ asset pipeline compatibility:
    ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))

    # "/fallback/" + [version_name, "default.png"].compact.join('_')
  end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  version :thumb do
    process resize_to_limit: [200, 200]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_whitelist
    %w(jpg jpeg gif png)
  end

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

end

相关观点:

<div class="jumbotron">
  <%= image_tag @listing.images.first.url %>
</div>

0 个答案:

没有答案