ruby-on-rails-5 - 忽略丢失的循环图像并显示当前的图像 - 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
解决方案
我认为您正在寻找从选定产品中找到任何营销图片?您可以创建一个范围来查找非空白的关联图像:
scope :with_marketing_images, -> { joins(:marketing_image).where.not(marketing_image.url: '') }
那么你的轮播可以是:
@marketing_images = @products.with_marketing_images
推荐阅读
- r - R data.frame 因子而不是级别
- laravel - 一个redis实例可以订阅其他redis实例吗?
- java - 使用 Jboss 阅读 PropertyPlaceholderConfigurer 类路径 Spring
- javascript - 谷歌图表列名覆盖
- swift - 自定义沙盒 NSSavePanel 警报
- machine-learning - 与随机森林学习器的高方差
- ios - 如何在 viewmodel 中处理 RxSwift observable
- image - 找到docker层对应的docker镜像
- c - C中#define的未定义行为
- python - 如何在 python 3.7 中加密和解密字符串?