Paperclip - Running a method after the file is saved?

霸气de小男生 提交于 2019-12-05 02:39:39

You can't read paperclip file in a callback as it's not saved to filesystem yet (or butt). Why, I'm not exactly sure.

EDIT: Reason is that paperclip writes out the file via after_save callback. That callback happens after after_create

However you can get the file payload for your processing. For example:

class Foo < ActiveRecord::Base

  has_attached_file :csv

  after_create :process_csv

  def process_csv
    CSV.parse(self.csv.queued_for_write[:original].read)
    # .. do stuff
  end

end

I had to do this 2 minutes ago. Hope this helps.

Adding this answer for visibility. A previous comment by @Jonmichael Chambers in this thread solved the problem for me.

Change the callback from after_save/after_create to after_commit

I think the problem might be related to the order of callbacks.

As discussed in other answers, the attachment file is indeed physically saved to disk in an after_save callback defined in Paperclip which is added to the model class at the point of has_attached_file call.

So you must ensure that your own after_save callbacks (that want to deal with the uploaded file) are defined after the has_attached_line.

Note: the after_create callback indeed cannot be used at all as it is called before after_save.

Take a look at the Paperclip post processing events callbacks. You should be able to call after_post_process to do your extra file info extraction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!