3

How can I skip post processing based on a virtual attribute?

My virtual attribute is always nil in the before_asset_post_process callback

Create

attachment = Attachment.create(asset: File.open(file.png), :skip_thumb => 1)

Attachable model

class Attachment < AR::Base
 attr_accessor :skip_thumb

  has_attached_file :asset, :styles => lambda  { |attachment| { :thumb =>  ["100>", 'jpg'] ,
                                                                       :thumb_big =>   ["200>", 'jpg']
                                                                     }
  before_asset_post_process :proceed_or_cancel

  def proceed_or_cancel
    #self.skip_thumb is always nil
    if (self.skip_thumb.present?)
      return false 
    end
  end 

end
recursive_acronym
  • 2,981
  • 6
  • 40
  • 59
  • It seems to be because attributes don't get set until after before_asset_post_process – recursive_acronym Nov 02 '12 at 23:04
  • I found details in this issue in the Paperclip repo, which shed light on the issue https://github.com/thoughtbot/paperclip/issues/1279 "The timing of the processing depends on when the attachment is mass-assigned, since processing happens on assignment, not on save." – ethaning Mar 02 '21 at 13:18

2 Answers2

0

Do you use attr_accessible in your Attachment model? If so, and if it does not include skip_thumb this fails (silently) when you try to assign it via mass assignment.

The opposite of attr_accessible is attr_protected, if you have skip_thumb in there, remove it.

doesterr
  • 3,955
  • 19
  • 26
0

The assignment of :asset will happen before the assignment of :skip_thumb if it's first in the hash that you pass to Attachment.create(). Therefore, it will work if you change your code to:

attachment = Attachment.create(skip_thumb: 1, asset: File.open(file.png))

I hope this is not too late to be useful...

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
mushishi78
  • 355
  • 3
  • 10