【问题标题】:Update paperclip attachment with a same name file用同名文件更新回形针附件
【发布时间】:2012-10-23 15:33:41
【问题描述】:

我有一个带有回形针附件的模型。当我尝试用另一个图像更新模型时,一切正常,除非新文件与旧文件同名。

我猜回形针不明白这是一个新文件,即使文件名相同。

你有想法让它发挥作用吗?

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    我无法找到一个优雅的解决方案,但这是我如何让它工作的:

    在你的模型上有一个 attr_accessor 布尔标志,当为真时调用回形针保存方法来强制更新。

    class MyModel < ActiveRecord::Base
       # paperclip attachment
       has_attached_file :image, { ... }
    
       attr_accessor :creative_uploaded
    
       before_save :upload_new_creative_if_necessary
    
       private
    
       def upload_new_creative_if_necessary
         if creative_uploaded
           # force update of the creative
           image.save
         end
       end
    end
    

    在我的控制器中,当帖子与文件一起出现时,我设置了该标志:

    @my_instance = MyModel.new( params[:my_model] )
    @my_instance.creative_uploaded if params[:my_model][:image]
    
    # ActiveRecord save/handle validations logic as normal
    

    【讨论】:

      【解决方案2】:

      接受的答案确实有效。然而;我不喜欢它与特定领域的联系,实际上有很多地方需要这个功能。在大多数情况下,以下问题应该有效(它假设您没有任何在其名称中使用 file_name 的非回形针列)。

      module AttachmentUpdatable
        extend ActiveSupport::Concern
      
        included do
          before_save :check_for_and_save_images
        end
      
        def check_for_and_save_images
          return if self.new_record?
          self.changed_attributes.each do |attr|
            attr_name = attr[0].to_s
            next unless attr_name.include?('file_name') # Yes, this is an assumption
            image_col = attr_name.gsub('_file_name','')
            self.send(image_col).save
          end
        end
      
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-26
        • 1970-01-01
        • 2016-01-20
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多