首页 > 解决方案 > 忽略丢失的循环图像并显示当前的图像 - Rails 5 Active Storage

问题描述

我有一个轮播从附加的 has_one (marketing_image) Active Storage 文件上传方法中获取图像。如果未上传营销图片,我希望轮播仍然显示。

显然,我需要至少有一个轮播才能工作,但我想找到一种方法来跳过数组中任何丢失的图像并仅显示已上传的图像。我正在使用 Rails 5。谢谢

我尝试了以下方法,但它们隐藏了整个轮播,这不是我想要的。

除非(product.marketing_image != nil?)

除非!product.marketing_image.blank?

模型

has_one_attached :product_image
has_one_attached :marketing_image

节目

 <%= image_tag product.marketing_image.variant(combine_options: {resize: '1000x450^', gravity: 'center', extent: '1000x450^'}), class: 'img-fluid'%>

控制器

def index
  @products = Product.all
  @categories = Category.all
end

标签: ruby-on-rails-5

解决方案


我认为您正在寻找从选定产品中找到任何营销图片?您可以创建一个范围来查找非空白的关联图像:

scope :with_marketing_images, -> { joins(:marketing_image).where.not(marketing_image.url: '') }

那么你的轮播可以是:

@marketing_images = @products.with_marketing_images

另请参阅Rails 范围的 IS NOT NULL 并且不是空/空白?


推荐阅读