Rails图片变体不存在时触发重设大小:重复入队问题求助
问题:图片变体生成任务重复入队
我想实现一个辅助方法,逻辑是如果图片变体已存在就直接展示,否则把图片重设大小的任务加入队列。但现在每次页面加载时这个任务都会被重复入队,原本以为首次执行任务后变体已经存在,就不会再重复执行了。
相关代码
application_helper.rb
def render_img(img, params, opts = {}) variant = img.variant(resize_to_fill: params, auto_orient: true, format: :jpg) if img.service.exist?(variant.key) image_tag variant, opts else ResizePhotoJob.perform_later(img.blob, resize_cmd: params) image_tag img, opts end end
resize_photo_job.rb
# frozen_string_literal: true class ResizePhotoJob < ApplicationJob queue_as :default def perform(file, resize_cmd:nil) if resize_cmd.nil? file.variant(auto_orient: true, format: :jpg, quality: 90).processed else file.variant(resize_to_fit: resize_cmd, auto_orient: true, format: :jpg).processed end end end
问题根源
你在辅助方法里创建变体用的是resize_to_fill参数,但在Job里生成变体用的是resize_to_fit。这两个不同的处理参数会生成完全不同的variant key,所以每次页面加载时,img.service.exist?(variant.key)都会返回false——因为Job实际生成的变体key和你检查的key根本不是同一个,自然会重复触发入队操作。
修复方案
把Job里的resize_to_fit改成和辅助方法一致的resize_to_fill,确保两边生成的变体参数完全相同,这样生成的key才会匹配:
修改后的resize_photo_job.rb:
# frozen_string_literal: true class ResizePhotoJob < ApplicationJob queue_as :default def perform(file, resize_cmd:nil) if resize_cmd.nil? file.variant(auto_orient: true, format: :jpg, quality: 90).processed else # 把resize_to_fit改为resize_to_fill,和helper保持一致 file.variant(resize_to_fill: resize_cmd, auto_orient: true, format: :jpg).processed end end end
额外注意:如果params是尺寸数组(比如[800,600]),要确保两边传递和使用的方式完全一致,避免因为参数格式差异导致key不匹配。
内容的提问来源于stack exchange,提问作者tfantina
相关产品推荐
相关产品推荐

