【问题标题】:Rails4 and Paperclip 4.0.2 callback turns as infinite loopRails4 和 Paperclip 4.0.2 回调变成无限循环
【发布时间】:2014-10-17 09:58:36
【问题描述】:

我将回形针设置为我的“文档”模型,具有相当标准的配置。它工作得很好,但我想在后台作业中分离额外的样式文件生成(使用 Resque)。

(我想停止创建 :orginal 样式以手动分配文件,但似乎不可能)

所以,要在后台作业中提取样式,我首先要停止回形针样式处理器。 然后我叫reprocess!在 after_save 回调中生成它们。

这样做会将更新操作置于无限循环中,而这正是我调用重新处理的时候!

这是我的文档模型(为便于理解而简化)

class Document < ActiveRecord::Base
  has_attached_file :attachment

   before_post_process :stop_process
   after_save :process_styles #same result with after_update (since user can only add attachment when updating profile)

   # Kill all paperclip styles
   #still generate the :orginal style. Block that too to copy it manually from remote folder would be nice 
   def stop_process
     false
   end

  #call for the generation of the additional styles (:medium, :thumb) 
  def process_styles
    Profile.processDocumentJob(id)
  end

  #will be a background job
  def self.processDocumentJob(id)
    document = Document.find(id)
    document.attachment.reprocess!
    document.save(validate: false)
  end
end

尽管我的 document.save(validate: false),更新期间的流程循环。 我尝试了 after_update 回调,调整了我的代码和条件,但没有成功。 提前感谢您的宝贵帮助

【问题讨论】:

    标签: ruby-on-rails paperclip infinite-loop


    【解决方案1】:

    我知道这是一个老问题,但今天发生在我身上并以这种方式解决了......有点 hacky 顺便说一句......我并不为我的解决方案感到自豪。这适用于 Rails 5。

    1. 为我的模型“skip_callbacks”添加了一个虚拟属性
    2. 添加了一个方法来检查属性是否为真“should_skip_callbacks?”
    3. 在我的回调中添加了“除非::should_skip_callbacks?”条件
    4. 在回形针重新处理之前,将虚拟属性“skip_callbacks”设置为 true

    这是我的模型的简化版本:

    class Organization < ApplicationRecord 
    
      attr_accessor :skip_callbacks
      has_attached_file :logo, styles: { header: "380x160>" }
      validates_attachment :logo, content_type: {content_type: ['image/png','image/jpg','image/gif']}
    
      after_save :reprocess_logo, unless: :should_skip_callbacks?
    
      def should_skip_callbacks?
        self.skip_callbacks
      end   
    
      def reprocess_logo
        self.skip_callbacks = true
        self.logo.reprocess!
      end   
    
    
    end
    

    【讨论】:

      猜你喜欢
      • 2013-11-30
      • 1970-01-01
      • 2011-09-21
      • 2017-09-21
      • 2020-08-21
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多